510 likes | 677 Views
INHERITANCE Class Hierarchies Extending Objects Abstract Methods Abstract Classes Overriding Methods protected. Introduction.
E N D
INHERITANCE • Class Hierarchies • Extending Objects • Abstract Methods • Abstract Classes • Overriding Methods • protected
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
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
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)
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
Inheritance Animal Reptile Mammal Fish Dog Cat Moose • 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, andMoose “inherit from” Mammal
Car SportsCar Van Limo 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
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., Mammalis 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)
Inheriting Capabilities and Properties • Subclass inheritsall public capabilities of its superclass • if Animals eat and sleep, then Reptiles, Mammals and Fish eat and sleep • ifCars move, then SportsCars move! • anything superclass can do, subclass can do • Subclass specializes its superclass • by adding new methods, overridingexisting methods, and defining “abstract”methodsdeclared 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?
Inheritance Defined Superclass • When one class re-uses the capabilities defined in another class. • The new subclass gains all the methods and attributes of the superclass. Superclass Vehicle Subclass Car Truck
Student CollegeStudent CS15Student Inheritance Example • Studentinheritance 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.
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())
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.
Two Types of Inheritance • Extension • Adds attributes and methods • Redefinition (Method Overriding) • Changes/modifies existing methods, specializing as needed
Inheritance Example: Bank Accounts • Consider a primitive bank • account which allows only three kinds of transactions: • Deposits • Withdrawals • Ability to check current balance
The Base Class Bank_Account Bank_Account setBalance • balance GetBalance deposit withdraw
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; }
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
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
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.
SavingsAccount • RATE • MIN_BALANCE calcInterest Illustration of Inheritance BankAccount • balance GetBalance deposit setBalance withdraw
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; } }
BankAccount SavingsAccount 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")); } }
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,
SavingsAccount • RATE • MIN_BALANCE calcInterest Illustration of Redefinition DeluxeSavings allowOverdraft • overdraftOK • OVERDRAFTCHARGE withdraw
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
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; super & this
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
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 upas needed to find a match
DeluxeSavings ds; ds = new DeluxeSavings(); ds.deposit(1000.00); ds.deposit( ds.calcInterest()); ds.withdraw(500.00) ds.setOverdraftOK(true); ds.withdraw(2000.00); Method Resolution BankAccount balance deposit withdraw getBalance SavingsAccount RATE MIN_BALANCE calcInterest DeluxeSavings overdraftOK OVERDRAFT_CHARGE setOverdraftOK setOverdraftNOT withdraw
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.
protectedInstance 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!
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!
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 abstractbehaviorand 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!
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 Cars know how to move, but each moves differently • There would be nocode 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”
Abstract Methods, continued • Reserved word abstract is modifierthat says everysubclass has specific capability, but superclass is unaware of implementationof 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 abstractmethod mustitself be declared abstract
Abstract Classes • Possible definition of Car • all Cars 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 abstractmethods it can be instantiated • it is concrete! publicabstractclass Car { // define to provide moving behavior abstractpublic void move(); } note the semicolon! // This will not compile. Car myCar = new Car();
What’s the difference between move and startEngine? Code: Let’s make some Cars! (1 of 3) publicabstractclass 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
Code: Let’s make some Cars! (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…
Code: Let’s make some Cars! (3 of 3) public class SportsCarextendsCar { 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
Syntax: Declaring/Defining a Subclass • To declare subclass of Car, we say that it extendssuperclass 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?
Superclass Constructors • SportsCar is responsible for initializing instance variables it defines: _top = new ConvertibleTop(); • ConvertibleTop is a property specific to SportsCars, so it is initialized in the constructor for SportsCar • Likewise, Caris 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
Syntax: superclass Constructors • Use reserved word superto call superclass constructor • it is as if superclass’ name issuper 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(); }
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!
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()
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 startEnginereplacesthe one in superclass • must be declared identically (in name and parameter list!) — check documentation • otherwise, nothing special about declaration
How does Java call methods? • We can use Vanin 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 Vanis created, its class determines which methods will be called
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 callsCar’s definition • for Van’s move(), Java would call Van’s definition Object (all classes that you write are automatically subclasses of Java’s Object class) Car move startEngine Van move
Let’s move some Cars (1 of 2) • 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 • stringsare words, phrases, or any other sequence of alphanumeric characters • more on strings later
Let’s move some Cars (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?