Download presentation
Presentation is loading. Please wait.
Published byDulcie Conley Modified over 9 years ago
2
September 21, 2004 Inheritance 1 of 30 INHERITANCE Class Hierarchies Extending Objects Abstract Methods Abstract Classes Overriding Methods protected
3
September 21, 2004 Inheritance 2 of 30 Introduction In real situations either when modeling real world objects such as vehicles, animals, etc. or when modeling abstract data structures such as queues, stacks, collections, windows, menu boxes the structure of different object families can be viewed as a kind of "family" tree. Java like most OO languages allows us to use these types of relationships to reuse code and functionality by making classes that use characteristics of "parent" classes
4
September 21, 2004 Inheritance 3 of 30 Defining the Differences Classes often share capabilities We want to avoid re-coding these capabilities Reuse of these would be best to Improve maintainability Reduce cost Improve “real world” modeling
5
September 21, 2004 Inheritance 4 of 30 Everyone wants a car nowadays Java TAs needs to get around? Need a Limo get back and forth from School But, csc2010 TAs want a vehicle as well they’re sick of walking to class so they need a van, a vehicle that’s big enough to fit all of them Mr. Henry, on the other hand, has his own wish list he needs to get places in a hurry he likes driving with the top down so he needs a convertible sportscar that moves fast (so he can make his airplane)
6
September 21, 2004 Inheritance 5 of 30 Similarities and Differences What do these three vehicles have in common? they’re all cars! all can move all have an engine all have doors all have one driver all hold a number of passengers What about these three vehicles is different? the sportscar: convertible top, 2 doors, moves really fast, holds small number of people the van: high top, 5 doors (one of which slides open), moves at moderate speed, holds large number of people the Limo: normal top, 2 doors, moves slowly, holds moderate number of people
7
September 21, 2004 Inheritance 6 of 30 Inheritance models “is a” relationships object “is an” other object if it can behave in the same way Inheritance uses similarities and differences to model groups of related objects Where there’s Inheritance, there’s an Inheritance Hierarchy of classes Mammal “is an” Animal Cat “is a” Mammal transitive: a Cat “is an” Animal, too We can say: Reptile, Mammal and Fish “inherit from” Animal Dog, Cat, and Moose “inherit from” Mammal Inheritance Animal Reptile Mammal Fish Cat Moose Dog
8
September 21, 2004 Inheritance 7 of 30 Inheritance, even in the car industry! Wow! What does this have to do with cars? a SportsCar “is a” Car a Limo “is a” Car you get the picture... We call this a tree diagram, with Car as the “root” and SportsCar, Limo, Van as “leaves” (yes, it’s an upside down tree...) How can this help Mr Henry and the TAs? First let’s discuss some important facts about Inheritance Car Van Limo SportsCar
9
September 21, 2004 Inheritance 8 of 30 Superclasses and Subclasses Inheritance is a way of: organizing information grouping similar classes modeling similarities between classes creating a taxonomy of objects Animal is called superclass or base class or parent class in car example, Car is called superclass Fish is called subclass or derived class or child class in car example, SportsCar is subclass Any class can be both at same time e.g., Mammal is superclass of Moose and subclass of Animal Can only inherit from one superclass in Java otherwise, no limit to depth or breadth of class hierarchy C++ allows a subclass to inherit from multiple superclasses (error-prone)
10
September 21, 2004 Inheritance 9 of 30 Inheriting Capabilities and Properties Subclass inherits all public capabilities of its superclass if Animal s eat and sleep, then Reptile s, Mammal s and Fish eat and sleep if Car s move, then SportsCar s move! anything superclass can do, subclass can do Subclass specializes its superclass by adding new methods, overriding existing methods, and defining “abstract” methods declared by parent we’ll see this in a few slides! Superclass factors out capabilities common to its subclasses subclasses described by differences from superclass As a general pattern, subclasses: inherit public capabilities (methods) inherit private properties (instance variables) but do not have access so what properties do subclasses inherit?
11
September 21, 2004 Inheritance 10 of 30 Inheritance Defined When one class re-uses the capabilities defined in another class. The new subclass gains all the methods and attributes of the superclass. Vehicle Car Truck Superclass Subclass
12
September 21, 2004 Inheritance 11 of 30 Inheritance Example Student inheritance hierarchy: Student as baseclass CollegeStudent as Student ’s subclass CS15Student as subclass of CollegeStudent Student has one capability (or method) study() which works by: going home, opening a book, and reading 50 pages. Student CollegeStudent CS15Student
13
September 21, 2004 Inheritance 12 of 30 Inheritance Example (cont.) CollegeStudent “is a” Student, so inherits study() But it overrides the study() method to work by: going to the Rock, studying for a midterm, and doing a problem set Finally the CS15Student also knows how to study() (it study() s the same way a CollegeStudent does) However adds two capabilities: gitDown() and gitFunky() Each subclass specializes its superclass Student knows how to study(), so all subclasses in hierarchy know how to study() But the CollegeStudent does not study() the same way a Student does And the CS15Student has some capabilities that neither Student nor CollegeStudent have ( gitDown() and gitFunky() )
14
September 21, 2004 Inheritance 13 of 30 Benefits of Inheritance Saves effort of “reinventing the wheel” Allows us to build on existing code, specializing without having to copy it, rewrite it, etc. To create the subclass, we need to program only the differences between the superclass and the subclass that inherits from it. Allows for flexibility in class definitions.
15
September 21, 2004 Inheritance 14 of 30 Two Types of Inheritance Extension Adds attributes and methods Redefinition (Method Overriding) Changes/modifies existing methods, specializing as needed
16
September 21, 2004 Inheritance 15 of 30 Inheritance Example: Bank Accounts Consider a primitive bank account which allows only three kinds of transactions: Deposits Withdrawals Ability to check current balance
17
September 21, 2004 Inheritance 16 of 30 The Base Class Bank_Account Bank_Account balance withdraw deposit setBalance GetBalance
18
September 21, 2004 Inheritance 17 of 30 A Superclass Bank_Account class BankAccount { private double balance; public BankAccount() { setBalance(0); } // constructor public void setBalance(double balance) { this.balance = balance; System.out.println( "New balance now: "+ getBalance()); } public double getBalance() { return balance; }
19
September 21, 2004 Inheritance 18 of 30 A Superclass Bank_Account class BankAccount { private double balance; public BankAccount() { setBalance(0); } // constructor public void setBalance(double balance) { this.balance = balance; System.out.println( "New balance now: "+ getBalance()); } public double getBalance() { return balance; } Note: balance is private – accessed only by special methods for set and get
20
September 21, 2004 Inheritance 19 of 30 A Superclass Bank_Account // class BankAccount continued public void deposit(double amt) { setBalance(getBalance() + amt); } public void withdraw(double amt) { if(getBalance() < amt) { amt = getBalance(); System.out.println ("Can only withdraw " + amt); } setBalance(getBalance() - amt); } } // BankAccount
21
September 21, 2004 Inheritance 20 of 30 Inheritance by Extension Imagine that we wish to create a new kind of Bank Account that is: Identical to the base class in all respects, except one We want to add the ability for the account to earn interest Without inheritance, we’d have to write it from scratch, duplicating code, etc. With inheritance, we need code only the new capability and inherit the rest.
22
September 21, 2004 Inheritance 21 of 30 Illustration of Inheritance BankAccount balance withdraw deposit GetBalance setBalance RATE MIN_BALANCE calcInterest SavingsAccount
23
September 21, 2004 Inheritance 22 of 30 Inheritance by Extension class SavingsAccount extends BankAccount { public final static double RATE = 0.023; public final static double MIN_BALANCE = 500.00; public double calcInterest() { double interest; if (getBalance() >= MIN_BALANCE) interest = getBalance()*RATE; else interest = 0.00; return interest; }
24
September 21, 2004 Inheritance 23 of 30 Using Subclasses class BankExample1 { public static void main(String args[]) { SavingsAccount mySavings; double myInterest; mySavings = new SavingsAccount(); mySavings.deposit(500.00); myInterest = mySavings.calcInterest(); mySavings.deposit(myInterest); mySavings.withdraw( IOGadget.readDouble( "Enter amount to withdraw")); } BankAccount SavingsAccount
25
September 21, 2004 Inheritance 24 of 30 Inheritance by Redefinition Imagine that we wish to create a new kind of Savings Account that is identical to Savings Account in all respects, except: We want to change the way in which withdrawals are handled The base class already handles withdrawals, but now we want a subclass that does them differently. Without inheritance, we’d have to rewrite it from scratch. With inheritance, we need code only the new way that we want withdrawals to work,
26
September 21, 2004 Inheritance 25 of 30 Illustration of Redefinition RATE MIN_BALANCE calcInterest SavingsAccount overdraftOK OVERDRAFTCHARGE allowOverdraft DeluxeSavings withdraw
27
September 21, 2004 Inheritance 26 of 30 Inheritance with Redefinition class DeluxeSavings extends SavingsAccount { private boolean overdraftOK; public final static double OVERDRAFTCHARGE = 20.0; public DeluxeSavings() { super(); setOverdraftOK(false); } public void setOverdraftOK(boolean odok) { overdraftOK = odok; } public void withdraw(double amt) { if (overdraftOK) { setBalance(getBalance() - amt); if (getBalance() < 0) setBalance(getBalance() - OVERDRAFTCHARGE); } else { super.withdraw(amt); } } // withdraw } // DeluxeSavings
28
September 21, 2004 Inheritance 27 of 30 super & this super means “look in the superclass” Constructor: super(); Method: super.m(); Field: super.x; this means “look in this class” Constructor: this(); Method: this.m(); Field: this.x;
29
September 21, 2004 Inheritance 28 of 30 Using Subclasses class BankExample2 { public static void main(String args[]) { double interest, amt1, amt2; DeluxeSavings mds = new DeluxeSavings(); mds.deposit(250.00); amt1 = IOGadget.readDouble("Enter amount to withdraw"); mds.withdraw(amt1); mds.setOverdraftOK(true); interest = mds.calcInterest(); mds.deposit(interest); amt2 = IOGadget.readDouble("Enter amount to withdraw"); mds.withdraw(amt2); } // main } // Demo
30
September 21, 2004 Inheritance 29 of 30 Design & Use Declare common methods/attributes as high in the class hierarchy as possible All subclasses will inherit these capabilities Specialize (extend and redefine) in subclasses When a method is invoked, the request is serviced by the lowest, most specific class and moves up as needed to find a match When a method is invoked, the request is serviced by the lowest, most specific class and moves up as needed to find a match
31
September 21, 2004 Inheritance 30 of 30 Method Resolution DeluxeSavings ds; ds = new DeluxeSavings(); ds.deposit(1000.00); ds.deposit( ds.calcInterest()); ds.withdraw(500.00) ds.setOverdraftOK(true); ds.withdraw(2000.00); DeluxeSavings overdraftOK OVERDRAFT_CHARGE setOverdraftOK setOverdraftNOT withdraw BankAccount balance deposit withdraw getBalance SavingsAccount RATE MIN_BALANCE calcInterest
32
September 21, 2004 Inheritance 31 of 30 Summary of Inheritance Extension take a base class and add new capabilities to it (methods, fields). Redefinition (method overriding) takes a base class and redefines an existing method, implementing it in a new way in order to change capability or performance. Both allow us to code only the differences.
33
September 21, 2004 Inheritance 32 of 30 protected Instance Variables Answer: subclasses inherit protected variables! A variable that is declared protected by a superclass becomes part of the inheritance variable becomes available for subclasses to access as if it were their own in contrast, if an instance variable is declared private by a superclass, its subclasses won’t have access to it superclass could still provide protected access to its private instance variables via accessor and mutator methods How can I decide between private and protected ? use private if you want an instance variable to be encapsulated by superclass e.g., doors, windows, spark plugs use protected if you want an instance variable to be available for subclasses to change (and you don’t want to make the variable more generally accessible via accessor/mutator methods) e.g., engine, so that subclasses can soup it up!
34
September 21, 2004 Inheritance 33 of 30 Inheritance as Form of Abstraction Root of class hierarchy is most general object because it is superclass to every other object in hierarchy can always say much more about how a subclass behaves than how its superclass behaves e.g., can say more about how a Van behaves than how a Car behaves! The MysteryMachine ain’t just any Van!
35
September 21, 2004 Inheritance 34 of 30 Inherit This! 5 things you might find in an Inheritance Hierarchy: 1) superclass is too general to declare all behavior, so each subclass adds its own behavior 2) superclass legislates an abstract behavior and therefore delegates implementation to subclasses (see upcoming move method) 3) superclass specifies behavior, subclasses inherit behavior (see upcoming startEngine method) 4) superclass specifies behavior, subclasses choose to override behavior just because a subclass inherits a method, doesn’t mean that it must act in the same way as its superclass subclass can choose to reject its superclass’ implementation of any method and “do it my way” 5) superclass specifies behavior, subclasses choose to override behavior in part called partial overriding you’ll learn this next lecture!
36
September 21, 2004 Inheritance 35 of 30 Abstract Methods What if we know that all subclasses should have some capability, yet we don’t know how those subclasses will implement it? e.g., all Car s know how to move, but each moves differently There would be no code that could be written for that capability that would apply to every subclass Methods for which no implementation makes sense should be abstract abstract means it has no definition, only declaration declaration highlights important features of method - its name, class of instance it returns (or none), and number and class of its parameters (if any) this information comprises what is known as the method’s “signature”
37
September 21, 2004 Inheritance 36 of 30 Abstract Methods, continued Reserved word abstract is modifier that says every subclass has specific capability, but superclass is unaware of implementation of that capability superclass defines policy for subclasses to implement guarantees some subclass down in the hierarchy will implement method Although abstract methods have no implementation, they are not the same as empty methods can’t instantiate an abstract class, i.e., a class that has one or more abstract methods can instantiate a class with an empty method most empty methods that you’ll see will be constructors empty methods still need curly braces, abstract methods must not have curly braces, instead they must end in a semi-colon public void emptyMethod() { } abstract public void abstractMethod(); Any class which contains an abstract method must itself be declared abstract
38
September 21, 2004 Inheritance 37 of 30 Abstract Classes Possible definition of Car all Car s can move, but superclass does not say how superclass simply declares abstract methods, subclass must define all abstract methods in order to become concrete Abstract classes cannot be instantiated Once subclass has defined all abstract methods it can be instantiated it is concrete! public abstract class Car { // define to provide moving behavior abstract public void move(); } // This will not compile. Car myCar = new Car(); note the semicolon!
39
September 21, 2004 Inheritance 38 of 30 Code: Let’s make some Car s! (1 of 3) public abstract class Car { // properties of all Cars private Door _driverDoor; // protected, because subclasses // might want to soup up their Engine protected Engine _engine; // more properties go here public Car() { _driverDoor = new Door(); // initialize other variables here } // notice the semicolon at the end of the // abstract method declaration! This is // important! public abstract void move(); public void startEngine() { // code to start up engine } // more methods go here } // end of class Car What’s the difference between move and startEngine ?
40
September 21, 2004 Inheritance 39 of 30 Code: Let’s make some Car s! (2 of 3) - Now that we are defining move(), it looks like any other method public class Van extends Car { public Van() { super(); } public void move() { // code to move at a moderate speed } } // end of class Van public class Limo extends Car { public Limo() { super(); } public void move() { // code to just pitter along! } } // end of class Limo Note that neither Van nor Limo include the startEngine method. Think about what this means…
41
September 21, 2004 Inheritance 40 of 30 Code: Let’s make some Car s! (3 of 3) public class SportsCar extends Car { private ConvertibleTop _top; // more properties here public SportsCar() { super(); _top = new ConvertibleTop(); // initialize other variables here } public void move() { // code to move really fast } public void startEngine() { // code to start engine with the // gusto of a SportsCar! Vroom! } } // end of class SportsCar
42
September 21, 2004 Inheritance 41 of 30 Syntax: Declaring/Defining a Subclass To declare subclass of Car, we say that it extends superclass public class SportsCar extends Car Now, let’s look at constructor definition for SportsCar : public SportsCar() { super(); _top = new ConvertibleTop(); } What’s going on inside SportsCar ’s constructor?
43
September 21, 2004 Inheritance 42 of 30 Superclass Constructors SportsCar is responsible for initializing instance variables it defines: _top = new ConvertibleTop(); ConvertibleTop is a property specific to SportsCar s, so it is initialized in the constructor for SportsCar Likewise, Car is responsible for initializing its instance variables. some are private and encapsulated some are protected, so subclasses can use them! So... must call SportsCar ’s constructor and Car ’s constructor to make sure any inherited instance variables are initialized! How can I do that? Always have subclass constructor call superclass constructor! Note that the abstract superclass, Car, isn’t explicitly instantiated and only a subclass uses the superclass’ constructor
44
September 21, 2004 Inheritance 43 of 30 Syntax: super class Constructors Use reserved word super to call superclass constructor it is as if superclass’ name is super and you are calling its constructor (i.e., calling method with same name as class) public SportsCar() { super(); // rest of constructor elided } You’ll always use this pattern: call to superclass constructor must be first line of subclass constructor calling superclass constructor anywhere else is compile-time error because initializing subclass may presuppose initialized superclass then initialize any subclass instance variables In fact, is exactly the default constructor Java provides every class automatically don’t have to call super(); but a good habit { super(); }
45
September 21, 2004 Inheritance 44 of 30 super and Parameters In our example, Car takes no parameters in its constructor public Car() nothing between the parentheses! What if Car had a constructor that needed parameters to be passed to it? public Car(Driver driver) this Car expects a Driver ! Then SportsCar needs to pass Car ’s constructor a Driver so either SportsCar needs to create a Driver, or needs to take one as parameter public SportsCar(Driver driver) this SportsCar expects a Driver !
46
September 21, 2004 Inheritance 45 of 30 super and Parameters (continued) public SportsCar(Driver driver) { super(driver); } this SportsCar gets a Driver and passes it up to its superclass’ constructor! Note again that only a subclass will invoke the abstract superclass’ constructor and pass it its parameters What happens if you forget to call the superclass constructor here? Java automatically calls super(); for you But... latest definition for Car doesn’t have a constructor that takes no parameters So... Compile Error. Java complains that there is no constructor declared public Car()
47
September 21, 2004 Inheritance 46 of 30 Overriding (Redefining) Methods Subclasses can override, i.e., redefine inherited methods: can choose to reject their superclass’ implementation of any method this means they can write their own definitions for how to respond to messages sent to them Car declares a startEngine() method that subclasses can either inherit (not change) or override (change) public class SportsCar extends Car { // declarations and constructor elided public void startEngine() { // code to start engine with the gusto of // a SportsCar! Vroom! } } Definition of startEngine replaces the one in superclass must be declared identically (in name and parameter list!) — check documentation otherwise, nothing special about declaration
48
September 21, 2004 Inheritance 47 of 30 How does Java call methods? We can use Van in the same way we would use Car because it behaves like the superclass in that it responds to the same messages How does Java determine which method to call when move() message is sent to instance? this is where class of instance is important when instance of Van is created, its class determines which methods will be called
49
September 21, 2004 Inheritance 48 of 30 Method Resolution First, Java sees if instance’s class defines the method; if so, calls it If not, Java “walks up class inheritance tree” from subclass to superclass until it either finds method, in which case it calls inherited method doesn’t find method; this is compile-time error (sending message for which there is no method) This process is called method resolution. for Van ’s startEngine(), Java calls Car ’s definition for Van ’s move(), Java would call Van ’s definition Car move startEngine Van move Object (all classes that you write are automatically subclasses of Java’s Object class)
50
September 21, 2004 Inheritance 49 of 30 public class VanButton extends PushButton { private Van _van; /** * Not so clean to have button contain car, * so we associate button with car in * constructor. */ public VanButton(Van myVan) { super( "Van" ); _van = myVan; } public void release() { _van.move(); } } // end of class VanButton Typical constructor, except for "Van" "Van" is called a string strings are words, phrases, or any other sequence of alphanumeric characters more on strings later Let’s move some Car s (1 of 2)
51
September 21, 2004 Inheritance 50 of 30 Let’s move some Car s (2 of 2) public class SportsCarButton extends PushButton { private SportsCar _sportsCar; public SportsCarButton(SportsCar mySC) { super( "SportsCar" ); _sportsCar = mySC; } public void release() { _sportsCar.move(); } } // end of class SportsCarButton public class LimoButton extends PushButton { } // end of class LimoButton Moltar forgot to fill this class in… Can you do it?
52
September 21, 2004 Inheritance 51 of 30 Making the Program public class CarApp extends wheels.users.Frame { private Van _van; private VanButton _vanButton; private Limo _15mobile; private LimoButton _15Button; private SportsCar _sportsCar; private SportsCarButton _sportsButton; public CarApp() { super(); _van = new Van(); _vanButton = new VanButton(_van); _15mobile = new Limo(); _15Button = new LimoButton(_15mobile); _sportsCar = new SportsCar(); _sportsButton = new SportsCarButton(_sportsCar); // code to put buttons in different // locations on the screen } public static void main(String[] argv) { CarApp app = new CarApp(); } }// end of class CarApp remember to associate each button with the Car it’s expecting!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.