Upload
pavel
View
31
Download
2
Embed Size (px)
DESCRIPTION
Chapter 11 -- Inheritance. Jim Burns. The Concept of Inheritance. Since day one, you have been creating classes and instantiating objects that are members of those classes. - PowerPoint PPT Presentation
Citation preview
Chapter 11 -- InheritanceChapter 11 -- Inheritance
Jim BurnsJim Burns
The Concept of InheritanceThe Concept of Inheritance Since day one, you have been Since day one, you have been
creating classes and instantiating creating classes and instantiating objects that are members of those objects that are members of those classes.classes.
Programmers use a graphical Programmers use a graphical language to describe classes and language to describe classes and object-oriented processes—this object-oriented processes—this Unified Modeling LanguageUnified Modeling Language consists of many types of diagramsconsists of many types of diagrams
Class diagramClass diagram Is a visual tool that provides you with Is a visual tool that provides you with
an overview of a classan overview of a class It is a rectangle divided into three It is a rectangle divided into three
sectionssections• the top section contains the name of the the top section contains the name of the
classclass• The middle section contains the names The middle section contains the names
and data types of the attributesand data types of the attributes• The bottom section contains the The bottom section contains the
methodsmethods
The Employee class diagramThe Employee class diagram
EmployeeEmployee -empNum : int-empNum : int -empSal : double-empSal : double
+getEmpNum : int+getEmpNum : int +getEmpSal : double+getEmpSal : double +setEmpNum(int num) : void+setEmpNum(int num) : void +setEmpSal(double sal) : void+setEmpSal(double sal) : void
Another employee classAnother employee class Suppose that a new employee called Suppose that a new employee called
serviceRepserviceRep is hired and that, in is hired and that, in addition to employee number and addition to employee number and salary, he needs a territory.salary, he needs a territory.
Rather than creating a whole new Rather than creating a whole new class, you can create a new class class, you can create a new class that inherits the behaviors and that inherits the behaviors and attributes of the original employee attributes of the original employee classclass
This is reuse at its bestThis is reuse at its best
EmployeeEmployee -empNum : int-empNum : int -empSal : double-empSal : double +getEmpNum : int+getEmpNum : int +getEmpSal : double+getEmpSal : double +setEmpNum(int num) : void+setEmpNum(int num) : void +setEmpSal(double sal) : void+setEmpSal(double sal) : void
EmployeeWithTerritoryEmployeeWithTerritory -empTerritory : int-empTerritory : int +getEmpTerritory : int+getEmpTerritory : int +setEmpTerritory : void+setEmpTerritory : void
When you use inheritance you:When you use inheritance you: Save time because the Employee fields Save time because the Employee fields
and methods already existand methods already exist Save money because it takes less time to Save money because it takes less time to
create a class that uses structure in old create a class that uses structure in old classesclasses
Reduce errors because the Employee Reduce errors because the Employee methods already have been used and methods already have been used and testedtested
Reduce the amount of new learning Reduce the amount of new learning required to use the new class, because required to use the new class, because you have used the Employee methods on you have used the Employee methods on simpler objects and already understand simpler objects and already understand how they workhow they work
Base classesBase classes Classes from which other classes Classes from which other classes
inherit attributes or methodsinherit attributes or methods Classes that inherit from base Classes that inherit from base
classes are called classes are called derived classesderived classes A base class is also called a A base class is also called a
superclasssuperclass A derived class is also called a A derived class is also called a
subclasssubclass You can also use the termsYou can also use the terms parent parent
class class andand child class child class
public class ASubClass extends ASuperClasspublic class ASubClass extends ASuperClass{{ public ASubClass()public ASubClass() {{ System.out.println("In subclass System.out.println("In subclass
constructor");constructor"); }}}}
public class ASuperClasspublic class ASuperClass{{ public ASuperClass()public ASuperClass() {{ System.out.println("In superclass System.out.println("In superclass
constructor");constructor"); }}}}
Extending ClassesExtending Classes You use the keyword You use the keyword extendsextends to to
achieve inheritance in Javaachieve inheritance in Java Example:Example:Public class EmployeeWithTerritory Public class EmployeeWithTerritory
extends Employeeextends Employee You used the You used the extends JAppletextends JApplet
throughout Chapters 9 and 10—throughout Chapters 9 and 10—every JApplet that you wrote is a every JApplet that you wrote is a child of the JApplet classchild of the JApplet class
Object instantiationObject instantiation You instantiate an object with a statement You instantiate an object with a statement
such assuch as employeeWithTerritory northernRep = employeeWithTerritory northernRep =
new EmployeeWithTerritory();new EmployeeWithTerritory();
Inheritance is a one-way proposition—a Inheritance is a one-way proposition—a child inherits from a parent, not the other child inherits from a parent, not the other way aroundway around
For example an For example an employeeemployee object cannot object cannot inherit from the inherit from the employeeWithTerritoryemployeeWithTerritory subclass—can’t access its methodssubclass—can’t access its methods
Getting field values from an objectGetting field values from an object
You can use any of the next You can use any of the next statements to get field values for the statements to get field values for the northernRepnorthernRep object: object:
northernRep.getEmpNum();northernRep.getEmpNum();northernRep.getEmpSal();northernRep.getEmpSal();northernRep.getEmpTerritory();northernRep.getEmpTerritory();
After the northernRep object is After the northernRep object is declared…declared…
Any of the following statements are Any of the following statements are appropriateappropriate
northernRep.setEmpNum(915);northernRep.setEmpNum(915);northernRep.setEmpSal(210.00);northernRep.setEmpSal(210.00);northernRep.setEmpTerritory(5);northernRep.setEmpTerritory(5);
The northernRep object has access to all The northernRep object has access to all the parent Employee class set methods, as the parent Employee class set methods, as well as its own class’s new set methodwell as its own class’s new set method
Child classes are more specificChild classes are more specific An An OrthodontistOrthodontist class and class and
PeriodontistPeriodontist class are children of the class are children of the DentistDentist parent class. parent class.
The The DentistDentist class does not have a class does not have a OrthodontistOrthodontist’s ’s applyBraces()applyBraces() method method or the or the PeriodontistPeriodontist’s ’s deepClean()deepClean() method.method.
However, However, OrthodontistOrthodontist objects and objects and PerodontistPerodontist objects have access to objects have access to the more general the more general DentistDentist methods methods
InstanceofInstanceof Instances of child classes are also Instances of child classes are also
instances of the parent classes of that instances of the parent classes of that classclass
The following are true:The following are true:If(myOrthodontist instanceof Dentist)…If(myOrthodontist instanceof Dentist)…If(myOrthodontist instanceof Orthodontist)…If(myOrthodontist instanceof Orthodontist)…
Overriding Superclass MethodsOverriding Superclass Methods When you extend a superclass, you create When you extend a superclass, you create
a subclass that inherits the superclass a subclass that inherits the superclass attributes and methodsattributes and methods
What do you do if you do not want these What do you do if you do not want these attributes and methods?attributes and methods?
You can write your ownYou can write your own In the musical instruments world a In the musical instruments world a play()play()
method would be very different for a method would be very different for a guitar as compared to a drumguitar as compared to a drum
This is called This is called polymorphismpolymorphism
PolymorphismPolymorphism Literally means ‘many forms’Literally means ‘many forms’ Consider an Consider an employeeemployee superclass superclass
with a with a printRateOfPay()printRateOfPay() method method For weekly employees the print For weekly employees the print
statement might bestatement might be• System.out.println(“Pay is “ + rateOfPay System.out.println(“Pay is “ + rateOfPay
+ “ per week”);+ “ per week”); For hourly employees the print For hourly employees the print
statement might bestatement might be• System.out.println(“Pay is “ + rateOfPay System.out.println(“Pay is “ + rateOfPay
+ “ per hour”);+ “ per hour”);
What do you do?What do you do? When you create a method in a child When you create a method in a child
class that has the same name and class that has the same name and argument list as a method in its argument list as a method in its parent class, you parent class, you override the override the methodmethod in the parent class in the parent class
When you use the method name with When you use the method name with a child object, the child’s version of a child object, the child’s version of the method is usedthe method is used
As an alternative…As an alternative… You could create and use a method You could create and use a method
with a different name…with a different name… But the classes are easier to write But the classes are easier to write
and understand if you use one and understand if you use one reasonable name for methods that reasonable name for methods that do essentially the same thing.do essentially the same thing.
In the example above, because we In the example above, because we are attempting to print the rate of are attempting to print the rate of pay for each object, pay for each object, printRateOfPay()printRateOfPay() is an excellent method name for this is an excellent method name for this function. function.
Can you think of any other reasons Can you think of any other reasons why polymorphism makes sense?why polymorphism makes sense?
When you have to change some When you have to change some aspect of behavior that is common to aspect of behavior that is common to all of the classes and that piece of all of the classes and that piece of behavior is inherited, then you have behavior is inherited, then you have to change it only in one place—not to change it only in one place—not ten placesten places
Understanding how Constructors Understanding how Constructors are called During Inheritanceare called During Inheritance
Consider the following:Consider the following:SomeClass anObject = new SomeClass();SomeClass anObject = new SomeClass();
Here you are instantiating an object of a Here you are instantiating an object of a subclass by invoking the SomeClass() subclass by invoking the SomeClass() constructorconstructor
You are actually calling at least two You are actually calling at least two constructors: the constructor for the base class constructors: the constructor for the base class and the constructor for the extended, derived and the constructor for the extended, derived class.class.
When a subclass constructor executes, the When a subclass constructor executes, the superclass constructor must execute first and superclass constructor must execute first and then the subclass constructorthen the subclass constructor
More…More… Often the execution of the superclass Often the execution of the superclass
constructor is transparent—nothing constructor is transparent—nothing call attention to the fact that the call attention to the fact that the superclass constructor is executing.superclass constructor is executing.
Question…Question… Suppose that Suppose that HourlyEmployeeHourlyEmployee is a is a
subclass of subclass of EmployeeEmployee.. When you create an object of When you create an object of
HourlyEmployeeHourlyEmployee called called clerkclerk What happens in terms of the What happens in terms of the
constructors involved???constructors involved???
public class ASuperClasspublic class ASuperClass{{public ASuperClass()public ASuperClass(){{System.out.println(“In superclass constructor”);System.out.println(“In superclass constructor”);}}}}public class ASubClass extends ASuperClasspublic class ASubClass extends ASuperClass{{public ASubClass()public ASubClass(){ { System.out.println(“In subclass constructor”);System.out.println(“In subclass constructor”);}}}}
public class DemoConstructorspublic class DemoConstructors{{public static void main(String[] args)public static void main(String[] args){{aSubClass child = new ASubClass90;aSubClass child = new ASubClass90;}}}}
The above produces the following The above produces the following output at the Command Promptoutput at the Command Prompt
C:\Java\java DemoConstructorsC:\Java\java DemoConstructorsIn superclass constructorIn superclass constructorIn subclass constructorIn subclass constructor
Using Superclass Constructors that Using Superclass Constructors that Require ArgumentsRequire Arguments
When you create a class and do not When you create a class and do not provide a constructor, Java provide a constructor, Java automatically supplies you with a automatically supplies you with a default constructor—one that never default constructor—one that never requires argumentsrequires arguments
When you write your own When you write your own constructor, you replace the constructor, you replace the automatically supplied versionautomatically supplied version
More on constructors…More on constructors… When all superclass constructors When all superclass constructors
have constructors that require have constructors that require arguments, you must make sure the arguments, you must make sure the subclass constructors provide those subclass constructors provide those argumentsarguments
In this case there is no default In this case there is no default superclass constructor without argssuperclass constructor without args
More on constructorsMore on constructors Your subclass constructors can Your subclass constructors can
contain any number of statements, contain any number of statements, but the first statement within each but the first statement within each subclass constructor must call the subclass constructor must call the superclass constructorsuperclass constructor
The format for the statement that The format for the statement that calls a superclass constructor iscalls a superclass constructor is
super(list of arguments);super(list of arguments);
Accessing Superclass MethodsAccessing Superclass Methods When two methods use the same When two methods use the same
name in both a superclass and a name in both a superclass and a subclass, the sublcass method subclass, the sublcass method overrides the supperclass method.overrides the supperclass method.
When you want the superclass When you want the superclass method to be used, you use the method to be used, you use the keyword keyword supersuper to access the to access the superclass methodsuperclass method
public class Customerpublic class Customer{{ private int idNumber;private int idNumber; private double balanceOwed;private double balanceOwed; public Customer(int id, double bal)public Customer(int id, double bal) {{ idNumber = id;idNumber = id; balanceOwed = bal;balanceOwed = bal; }} public void display()public void display() {{ System.out.println("Customer #" + System.out.println("Customer #" +
idNumber +idNumber + " Balance $" + balanceOwed);" Balance $" + balanceOwed); }}}}
public class PreferredCustomer extends Customerpublic class PreferredCustomer extends Customer{{ double discountRate;double discountRate; public PreferredCustomer(int id, double bal, public PreferredCustomer(int id, double bal,
double rate)double rate) {{ super(id, bal);super(id, bal); discountRate = rate;discountRate = rate; }} public void display()public void display() {{ super.display();super.display(); System.out.println("Discount rate is " + System.out.println("Discount rate is " +
discountRate);discountRate); }}}}
public class TestCustomerspublic class TestCustomers{{ public static void main(String[] args)public static void main(String[] args) {{ Customer oneCust = new Customer(124, Customer oneCust = new Customer(124,
123.45);123.45); PreferredCustomer onePCust = new PreferredCustomer onePCust = new PreferredCustomer(125, 3456.78, PreferredCustomer(125, 3456.78,
0.15);0.15); oneCust.display();oneCust.display(); onePCust.display();onePCust.display(); }}}}
Command PromptCommand Prompt C:\Java>Java TestCustomersC:\Java>Java TestCustomers Customer #124 Balance $123.46Customer #124 Balance $123.46 Chstomer #125 Balance $3456.78Chstomer #125 Balance $3456.78 Discount rate is 0.15Discount rate is 0.15
C:\Java>C:\Java>
public class DemoConstructorspublic class DemoConstructors{{ public static void main(String[] args)public static void main(String[] args) {{ ASubClass child = new ASubClass child = new
ASubClass();ASubClass(); }}}}
Learning about Information HidingLearning about Information Hiding
Information hiding is a way to Information hiding is a way to disallow certain attributes and disallow certain attributes and methods to be accessible within methods to be accessible within other classesother classes
We use the keyword We use the keyword privateprivate to make to make an attribute or method local to the an attribute or method local to the class and not accessible elsewhereclass and not accessible elsewhere
public class Studentpublic class Student{{ private int idNum;private int idNum; private double gpa;private double gpa; public int getIdNum;public int getIdNum; {{ return idNum;return idNum; }} public double getGpa()public double getGpa() {{ return gpa;return gpa; }} public void setIdNum(int num)public void setIdNum(int num) {{ idNum = num;idNum = num; }} public void setGpa(double gradePoint)public void setGpa(double gradePoint) {{ gpa = gradePoint;gpa = gradePoint; }}}}
Why won’t the following code Why won’t the following code work??work??
Suppose you write a main() method in Suppose you write a main() method in another class that does the following…another class that does the following…
Student someStudent = new Student();Student someStudent = new Student();someStudent.idNum = 812;someStudent.idNum = 812; Only methods contained within the Only methods contained within the
student class are allowed to alter Student student class are allowed to alter Student data:data:
someStudent.setIdNum(812);someStudent.setIdNum(812);
Remember…Remember… The methods in a subclass can use The methods in a subclass can use
all the fields (attributes, data) in an all the fields (attributes, data) in an inherited superclass as well as its inherited superclass as well as its methods, except….methods, except….
Those declared as….Those declared as….
This is called ….This is called ….
Are there other access modifiers??Are there other access modifiers??
Yes, Virginia, there are…Yes, Virginia, there are… Suppose that you want data to be Suppose that you want data to be
accessible to the class it was defined accessible to the class it was defined in as well as subclasses that extend in as well as subclasses that extend that class, but not in any other that class, but not in any other classes—that is you don’t want the classes—that is you don’t want the data to be publicdata to be public
Then, you use the keyword Then, you use the keyword protectedprotected
Using Methods you cannot Using Methods you cannot OverrideOverride
The three types of methods that you The three types of methods that you cannot override in a subclass are:cannot override in a subclass are:
staticstatic methods methods finalfinal methods methods Methods within Methods within finalfinal classes classes
A Subclass Cannot Override A Subclass Cannot Override staticstatic Methods in its SuperclassMethods in its Superclass
A subclass cannot override methods A subclass cannot override methods that are declared static in the that are declared static in the superclass.superclass.
Not even with the keyword Not even with the keyword supersuper See code below in which See code below in which
ProfessionalBaseballPlayerProfessionalBaseballPlayer extends extends BaseballPlayerBaseballPlayer
public class BaseballPlayerpublic class BaseballPlayer{{ private int jerseyNumber;private int jerseyNumber; private double battingAvg;private double battingAvg; public static void printOrigins()public static void printOrigins() {{ System.out.println("Abner Doubleday is System.out.println("Abner Doubleday is
often " +often " + "credited with inventing baseball");"credited with inventing baseball"); }}}}
public class ProfessionalBaseballPlayer public class ProfessionalBaseballPlayer extends BaseballPlayerextends BaseballPlayer
{{ double salary;double salary; public void printOrigins()public void printOrigins() {{ BaseballPlayer.printOrigins();BaseballPlayer.printOrigins(); System.out.println("The first professional System.out.println("The first professional
" +" + "major league baseball game was "major league baseball game was
played in 1871");played in 1871");
}}}}
In the above two frames of code..In the above two frames of code..
Java does not allow the Java does not allow the printOrigins()printOrigins() in in the subclass the subclass ProfessionalBaseballPlayerProfessionalBaseballPlayer to to override the static method override the static method printOrigins() printOrigins() in in the superclass BaseballPlayerthe superclass BaseballPlayer
This doesn’t work even if you declare the This doesn’t work even if you declare the method method printOrigins() printOrigins() in the subclass in the subclass ProfessionalBaseballPlayerProfessionalBaseballPlayer to be static, as to be static, as follows:follows:
public class ProfessionalBaseballPlayer public class ProfessionalBaseballPlayer extends BaseballPlayerextends BaseballPlayer
{{ double salary;double salary; public public staticstatic void printOrigins() void printOrigins() {{ supersuper.printOrigins();.printOrigins(); System.out.println("The first professional System.out.println("The first professional
" +" + "major league baseball game was "major league baseball game was
played in 1871");played in 1871");
}}}}
However, the following code will However, the following code will work:work:
public class ProfessionalBaseballPlayer public class ProfessionalBaseballPlayer extends BaseballPlayerextends BaseballPlayer
{{ double salary;double salary; public static void printOrigins()public static void printOrigins() {{ BaseballPlayer.printOrigins();BaseballPlayer.printOrigins(); System.out.println("The first professional System.out.println("The first professional
" +" + "major league baseball game was "major league baseball game was
played in 1871");played in 1871");
}}}}
When used with the following class:When used with the following class:Public class TestProPlayerPublic class TestProPlayer{{ public static void main(String[] public static void main(String[]
args)args) {{ professionalBaseballPlayer professionalBaseballPlayer
aYankee = new aYankee = new ProfessionalBaseballPlayer();ProfessionalBaseballPlayer();
aYankee.printOrigins();aYankee.printOrigins(); }}}}
The following output will be The following output will be producedproduced
C:\Java>Java TestProPlayerC:\Java>Java TestProPlayer Abner Doubleday is often credited with inventing baseballAbner Doubleday is often credited with inventing baseball The first professional major league baseball game was played in The first professional major league baseball game was played in
18711871
A Subclass Cannot Override A Subclass Cannot Override finalfinal Methods in its SuperclassMethods in its Superclass
A subclass cannot override methods A subclass cannot override methods that are declared that are declared finalfinal in the in the superclass.superclass.
Consider the classes BasketballPlayer Consider the classes BasketballPlayer and ProfessionalBasketballPlayer and ProfessionalBasketballPlayer belowbelow
These will generate an error at These will generate an error at compile timecompile time
public class BasketballPlayerpublic class BasketballPlayer{{ private int jerseyNumber;private int jerseyNumber; public final void printMessage()public final void printMessage() {{ System.out.println("Michael Jordan System.out.println("Michael Jordan
is the " +is the " + "greatest basketball player - and "greatest basketball player - and
that is final");that is final"); }}}}
public class public class ProfessionalBasketballPlayer extends ProfessionalBasketballPlayer extends BasketballPlayerBasketballPlayer
{{ double salary;double salary; public void printMessage()public void printMessage() {{ System.out.println("I have nothing System.out.println("I have nothing
to say");to say"); }}}}
Public void display(BasketballPlayer Public void display(BasketballPlayer bbplayer)bbplayer)
{{ bbplayer.printMessage();bbplayer.printMessage();}}
The above will cause the code created The above will cause the code created for for printMessage()printMessage() to be inserted to be inserted inlineinline and the practice is called and the practice is called inlininginlining..
A Subclass Cannot Override A Subclass Cannot Override Methods in a Methods in a finalfinal Superclass Superclass
You can also declare a class to be You can also declare a class to be finalfinal
Then all of its methods will be final as Then all of its methods will be final as well, regardless of what access well, regardless of what access modifiers precede the method name modifiers precede the method name in the melthod headerin the melthod header
public final class HideAndGoSeekPlayerpublic final class HideAndGoSeekPlayer{{ private int count;private int count; public void printRules()public void printRules() {{ System.out.println("You have to System.out.println("You have to
count to " + count +count to " + count + " before you start looking for " before you start looking for
hiders");hiders"); }}
public final class public final class ProfessionalHideAndGoSeekPlayerProfessionalHideAndGoSeekPlayer
extends HideAndGoSeekPlayerextends HideAndGoSeekPlayer{{ private double salary;private double salary;}}
The above two frames of code will The above two frames of code will generate a compiler error when you generate a compiler error when you try to compile the try to compile the ProfessionalHideAndGoSeekPlayerProfessionalHideAndGoSeekPlayer class.class.
The endThe end
Creating a Subclass Method that Creating a Subclass Method that Overrides a Superclass MethodOverrides a Superclass Method
Understanding the role of Understanding the role of Constructors in InheritanceConstructors in Inheritance
Understanding Inheritance when Understanding Inheritance when the Superclass Requires the Superclass Requires Constructor ArgumentsConstructor Arguments
Accessing an Overridden Accessing an Overridden Superclass Method from within a Superclass Method from within a
SubclassSubclass
Understanding the Understanding the protectedprotected Access ModifierAccess Modifier