Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11 -- Inheritance Jim Burns. The Concept of Inheritance Since day one, you have been creating classes and instantiating objects that are members.

Similar presentations


Presentation on theme: "Chapter 11 -- Inheritance Jim Burns. The Concept of Inheritance Since day one, you have been creating classes and instantiating objects that are members."— Presentation transcript:

1 Chapter 11 -- Inheritance Jim Burns

2 The Concept of Inheritance Since day one, you have been creating classes and instantiating objects that are members of those classes. Since day one, you have been creating classes and instantiating objects that are members of those classes. Programmers use a graphical language to describe classes and object-oriented processes—this Unified Modeling Language consists of many types of diagrams Programmers use a graphical language to describe classes and object-oriented processes—this Unified Modeling Language consists of many types of diagrams

3 Class diagram Is a visual tool that provides you with an overview of a class Is a visual tool that provides you with an overview of a class It is a rectangle divided into three sections It is a rectangle divided into three sections the top section contains the name of the classthe top section contains the name of the class The middle section contains the names and data types of the attributesThe middle section contains the names and data types of the attributes The bottom section contains the methodsThe bottom section contains the methods

4 The Employee class diagram Employee -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

5 Another employee class Suppose that a new employee called serviceRep is hired and that, in addition to employee number and salary, he needs a territory. Suppose that a new employee called serviceRep is hired and that, in addition to employee number and salary, he needs a territory. Rather than creating a whole new class, you can create a new class that inherits the behaviors and attributes of the original employee class Rather than creating a whole new class, you can create a new class that inherits the behaviors and attributes of the original employee class This is reuse at its best This is reuse at its best

6 Employee -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) : voidEmployeeWithTerritory -empTerritory : int -empTerritory : int +getEmpTerritory : int +getEmpTerritory : int +setEmpTerritory : void +setEmpTerritory : void

7 When you use inheritance you: Save time because the Employee fields and methods already exist Save time because the Employee fields and methods already exist Save money because it takes less time to create a class that uses structure in old classes Save money because it takes less time to create a class that uses structure in old classes Reduce errors because the Employee methods already have been used and tested Reduce errors because the Employee methods already have been used and tested Reduce the amount of new learning required to use the new class, because you have used the Employee methods on simpler objects and already understand how they work Reduce the amount of new learning required to use the new class, because you have used the Employee methods on simpler objects and already understand how they work

8 Base classes Classes from which other classes inherit attributes or methods Classes from which other classes inherit attributes or methods Classes that inherit from base classes are called derived classes Classes that inherit from base classes are called derived classes A base class is also called a superclass A base class is also called a superclass A derived class is also called a subclass A derived class is also called a subclass You can also use the terms parent class and child class You can also use the terms parent class and child class

9 public class ASubClass extends ASuperClass { public ASubClass() public ASubClass() { System.out.println("In subclass constructor"); System.out.println("In subclass constructor"); }}

10 public class ASuperClass { public ASuperClass() public ASuperClass() { System.out.println("In superclass constructor"); System.out.println("In superclass constructor"); }}

11 Extending Classes You use the keyword extends to achieve inheritance in Java You use the keyword extends to achieve inheritance in Java Example: Example: Public class EmployeeWithTerritory extends Employee You used the extends JApplet throughout Chapters 9 and 10— every JApplet that you wrote is a child of the JApplet class You used the extends JApplet throughout Chapters 9 and 10— every JApplet that you wrote is a child of the JApplet class

12 Object instantiation You instantiate an object with a statement such as You instantiate an object with a statement such as employeeWithTerritory northernRep = new EmployeeWithTerritory(); employeeWithTerritory northernRep = new EmployeeWithTerritory(); Inheritance is a one-way proposition—a child inherits from a parent, not the other way around Inheritance is a one-way proposition—a child inherits from a parent, not the other way around For example an employee object cannot inherit from the employeeWithTerritory subclass—can’t access its methods For example an employee object cannot inherit from the employeeWithTerritory subclass—can’t access its methods

13 Getting field values from an object You can use any of the next statements to get field values for the northernRep object: You can use any of the next statements to get field values for the northernRep object:northernRep.getEmpNum();northernRep.getEmpSal();northernRep.getEmpTerritory();

14 After the northernRep object is declared… Any of the following statements are appropriate Any of the following statements are appropriatenorthernRep.setEmpNum(915);northernRep.setEmpSal(210.00);northernRep.setEmpTerritory(5); The northernRep object has access to all the parent Employee class set methods, as well as its own class’s new set method The northernRep object has access to all the parent Employee class set methods, as well as its own class’s new set method

15 Child classes are more specific An Orthodontist class and Periodontist class are children of the Dentist parent class. An Orthodontist class and Periodontist class are children of the Dentist parent class. The Dentist class does not have a Orthodontist’s applyBraces() method or the Periodontist’s deepClean() method. The Dentist class does not have a Orthodontist’s applyBraces() method or the Periodontist’s deepClean() method. However, Orthodontist objects and Perodontist objects have access to the more general Dentist methods However, Orthodontist objects and Perodontist objects have access to the more general Dentist methods

16 Instanceof Instances of child classes are also instances of the parent classes of that class Instances of child classes are also instances of the parent classes of that class The following are true: The following are true: If(myOrthodontist instanceof Dentist)… If(myOrthodontist instanceof Orthodontist)…

17 Overriding Superclass Methods When you extend a superclass, you create a subclass that inherits the superclass attributes and methods When you extend a superclass, you create a subclass that inherits the superclass attributes and methods What do you do if you do not want these attributes and methods? What do you do if you do not want these attributes and methods? You can write your own You can write your own In the musical instruments world a play() method would be very different for a guitar as compared to a drum In the musical instruments world a play() method would be very different for a guitar as compared to a drum This is called polymorphism This is called polymorphism

18 Polymorphism Literally means ‘many forms’ Literally means ‘many forms’ Consider an employee superclass with a printRateOfPay() method Consider an employee superclass with a printRateOfPay() method For weekly employees the print statement might be For weekly employees the print statement might be System.out.println(“Pay is “ + rateOfPay + “ per week”);System.out.println(“Pay is “ + rateOfPay + “ per week”); For hourly employees the print statement might be For hourly employees the print statement might be System.out.println(“Pay is “ + rateOfPay + “ per hour”);System.out.println(“Pay is “ + rateOfPay + “ per hour”);

19 What do you do? When you create a method in a child class that has the same name and argument list as a method in its parent class, you override the method in the parent class When you create a method in a child class that has the same name and argument list as a method in its parent class, you override the method in the parent class When you use the method name with a child object, the child’s version of the method is used When you use the method name with a child object, the child’s version of the method is used

20 As an alternative… You could create and use a method with a different name… You could create and use a method with a different name… But the classes are easier to write and understand if you use one reasonable name for methods that do essentially the same thing. But the classes are easier to write and understand if you use one reasonable name for methods that do essentially the same thing. In the example above, because we are attempting to print the rate of pay for each object, printRateOfPay() is an excellent method name for this function. In the example above, because we are attempting to print the rate of pay for each object, printRateOfPay() is an excellent method name for this function.

21 Can you think of any other reasons why polymorphism makes sense? When you have to change some aspect of behavior that is common to all of the classes and that piece of behavior is inherited, then you have to change it only in one place—not ten places When you have to change some aspect of behavior that is common to all of the classes and that piece of behavior is inherited, then you have to change it only in one place—not ten places

22 Understanding how Constructors are called During Inheritance Consider the following: Consider the following: SomeClass anObject = new SomeClass(); Here you are instantiating an object of a subclass by invoking the SomeClass() constructor Here you are instantiating an object of a subclass by invoking the SomeClass() constructor You are actually calling at least two constructors: the constructor for the base class and the constructor for the extended, derived class. You are actually calling at least two constructors: the constructor for the base class and the constructor for the extended, derived class. When a subclass constructor executes, the superclass constructor must execute first and then the subclass constructor When a subclass constructor executes, the superclass constructor must execute first and then the subclass constructor

23 More… Often the execution of the superclass constructor is transparent—nothing call attention to the fact that the superclass constructor is executing. Often the execution of the superclass constructor is transparent—nothing call attention to the fact that the superclass constructor is executing.

24 Question… Suppose that HourlyEmployee is a subclass of Employee. Suppose that HourlyEmployee is a subclass of Employee. When you create an object of HourlyEmployee called clerk When you create an object of HourlyEmployee called clerk What happens in terms of the constructors involved??? What happens in terms of the constructors involved???

25 public class ASuperClass { public ASuperClass() { System.out.println(“In superclass constructor”); }} public class ASubClass extends ASuperClass { public ASubClass() { System.out.println(“In subclass constructor”); }} public class DemoConstructors { public static void main(String[] args) { aSubClass child = new ASubClass90; }}

26 The above produces the following output at the Command Prompt C:\Java\java DemoConstructors In superclass constructor In subclass constructor

27 Using Superclass Constructors that Require Arguments When you create a class and do not provide a constructor, Java automatically supplies you with a default constructor—one that never requires arguments When you create a class and do not provide a constructor, Java automatically supplies you with a default constructor—one that never requires arguments When you write your own constructor, you replace the automatically supplied version When you write your own constructor, you replace the automatically supplied version

28 More on constructors… When all superclass constructors have constructors that require arguments, you must make sure the subclass constructors provide those arguments When all superclass constructors have constructors that require arguments, you must make sure the subclass constructors provide those arguments In this case there is no default superclass constructor without args In this case there is no default superclass constructor without args

29 More on constructors Your subclass constructors can contain any number of statements, but the first statement within each subclass constructor must call the superclass constructor Your subclass constructors can contain any number of statements, but the first statement within each subclass constructor must call the superclass constructor The format for the statement that calls a superclass constructor is The format for the statement that calls a superclass constructor is super(list of arguments); super(list of arguments);

30 Accessing Superclass Methods When two methods use the same name in both a superclass and a subclass, the sublcass method overrides the supperclass method. When two methods use the same name in both a superclass and a subclass, the sublcass method overrides the supperclass method. When you want the superclass method to be used, you use the keyword super to access the superclass method When you want the superclass method to be used, you use the keyword super to access the superclass method

31 public 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 #" + idNumber + System.out.println("Customer #" + idNumber + " Balance $" + balanceOwed); " Balance $" + balanceOwed); }}

32 public class PreferredCustomer extends Customer { double discountRate; double discountRate; public PreferredCustomer(int id, double bal, double rate) public PreferredCustomer(int id, double bal, 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 " + discountRate); System.out.println("Discount rate is " + discountRate); }}

33 public class TestCustomers { public static void main(String[] args) public static void main(String[] args) { Customer oneCust = new Customer(124, 123.45); Customer oneCust = new Customer(124, 123.45); PreferredCustomer onePCust = new PreferredCustomer onePCust = new PreferredCustomer(125, 3456.78, 0.15); PreferredCustomer(125, 3456.78, 0.15); oneCust.display(); oneCust.display(); onePCust.display(); onePCust.display(); }}

34 Command Prompt C:\Java>Java TestCustomers C:\Java>Java TestCustomers Customer #124 Balance $123.46 Customer #124 Balance $123.46 Chstomer #125 Balance $3456.78 Chstomer #125 Balance $3456.78 Discount rate is 0.15 Discount rate is 0.15 C:\Java> C:\Java>

35 public class DemoConstructors { public static void main(String[] args) public static void main(String[] args) { ASubClass child = new ASubClass(); ASubClass child = new ASubClass(); }}

36 Learning about Information Hiding Information hiding is a way to disallow certain attributes and methods to be accessible within other classes Information hiding is a way to disallow certain attributes and methods to be accessible within other classes We use the keyword private to make an attribute or method local to the class and not accessible elsewhere We use the keyword private to make an attribute or method local to the class and not accessible elsewhere

37 public 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; }}

38 Why won’t the following code work?? Suppose you write a main() method in another class that does the following… Suppose you write a main() method in another class that does the following… Student someStudent = new Student(); someStudent.idNum = 812; Only methods contained within the student class are allowed to alter Student data: Only methods contained within the student class are allowed to alter Student data:someStudent.setIdNum(812);

39 Remember… The methods in a subclass can use all the fields (attributes, data) in an inherited superclass as well as its methods, except…. The methods in a subclass can use all the fields (attributes, data) in an inherited superclass as well as its methods, except…. Those declared as…. Those declared as….

40 This is called ….

41 Are there other access modifiers?? Yes, Virginia, there are… Yes, Virginia, there are… Suppose that you want data to be accessible to the class it was defined in as well as subclasses that extend that class, but not in any other classes—that is you don’t want the data to be public Suppose that you want data to be accessible to the class it was defined in as well as subclasses that extend that class, but not in any other classes—that is you don’t want the data to be public Then, you use the keyword protected Then, you use the keyword protected

42 Using Methods you cannot Override The three types of methods that you cannot override in a subclass are: The three types of methods that you cannot override in a subclass are: static methods static methods final methods final methods Methods within final classes Methods within final classes

43 A Subclass Cannot Override static Methods in its Superclass A subclass cannot override methods that are declared static in the superclass. A subclass cannot override methods that are declared static in the superclass. Not even with the keyword super Not even with the keyword super See code below in which ProfessionalBaseballPlayer extends BaseballPlayer See code below in which ProfessionalBaseballPlayer extends BaseballPlayer

44 public 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 often " + System.out.println("Abner Doubleday is often " + "credited with inventing baseball"); "credited with inventing baseball"); }}

45 public class ProfessionalBaseballPlayer extends 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 played in 1871"); "major league baseball game was played in 1871"); }}

46 In the above two frames of code.. Java does not allow the printOrigins() in the subclass ProfessionalBaseballPlayer to override the static method printOrigins() in the superclass BaseballPlayer Java does not allow the printOrigins() in the subclass ProfessionalBaseballPlayer to override the static method printOrigins() in the superclass BaseballPlayer This doesn’t work even if you declare the method printOrigins() in the subclass ProfessionalBaseballPlayer to be static, as follows: This doesn’t work even if you declare the method printOrigins() in the subclass ProfessionalBaseballPlayer to be static, as follows:

47 public class ProfessionalBaseballPlayer extends BaseballPlayer { double salary; double salary; public static void printOrigins() public static void printOrigins() { super.printOrigins(); super.printOrigins(); System.out.println("The first professional " + System.out.println("The first professional " + "major league baseball game was played in 1871"); "major league baseball game was played in 1871"); }}

48 However, the following code will work: However, the following code will work:

49 public class ProfessionalBaseballPlayer extends 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 played in 1871"); "major league baseball game was played in 1871"); }}

50 When used with the following class: Public class TestProPlayer { public static void main(String[] args) public static void main(String[] args) { professionalBaseballPlayer aYankee = new ProfessionalBaseballPlayer(); professionalBaseballPlayer aYankee = new ProfessionalBaseballPlayer(); aYankee.printOrigins(); aYankee.printOrigins(); }}

51 The following output will be produced C:\Java>Java TestProPlayer C:\Java>Java TestProPlayer Abner Doubleday is often credited with inventing baseball Abner Doubleday is often credited with inventing baseball The first professional major league baseball game was played in 1871 The first professional major league baseball game was played in 1871

52 A Subclass Cannot Override final Methods in its Superclass A subclass cannot override methods that are declared final in the superclass. A subclass cannot override methods that are declared final in the superclass. Consider the classes BasketballPlayer and ProfessionalBasketballPlayer below Consider the classes BasketballPlayer and ProfessionalBasketballPlayer below These will generate an error at compile time These will generate an error at compile time

53 public class BasketballPlayer { private int jerseyNumber; private int jerseyNumber; public final void printMessage() public final void printMessage() { System.out.println("Michael Jordan is the " + System.out.println("Michael Jordan is the " + "greatest basketball player - and that is final"); "greatest basketball player - and that is final"); }}

54 public class ProfessionalBasketballPlayer extends BasketballPlayer { double salary; double salary; public void printMessage() public void printMessage() { System.out.println("I have nothing to say"); System.out.println("I have nothing to say"); }}

55 Public void display(BasketballPlayer bbplayer) { bbplayer.printMessage(); bbplayer.printMessage();} The above will cause the code created for printMessage() to be inserted inline and the practice is called inlining.

56 A Subclass Cannot Override Methods in a final Superclass You can also declare a class to be final You can also declare a class to be final Then all of its methods will be final as well, regardless of what access modifiers precede the method name in the melthod header Then all of its methods will be final as well, regardless of what access modifiers precede the method name in the melthod header

57 public final class HideAndGoSeekPlayer { private int count; private int count; public void printRules() public void printRules() { System.out.println("You have to count to " + count + System.out.println("You have to count to " + count + " before you start looking for hiders"); " before you start looking for hiders"); }

58 public final class ProfessionalHideAndGoSeekPlayer extends HideAndGoSeekPlayer extends HideAndGoSeekPlayer{ private double salary; private double salary;}

59 The above two frames of code will generate a compiler error when you try to compile the ProfessionalHideAndGoSeekPlayer class. The above two frames of code will generate a compiler error when you try to compile the ProfessionalHideAndGoSeekPlayer class.

60 The end

61

62

63 Creating a Subclass Method that Overrides a Superclass Method

64 Understanding the role of Constructors in Inheritance

65 Understanding Inheritance when the Superclass Requires Constructor Arguments

66 Accessing an Overridden Superclass Method from within a Subclass

67 Understanding the protected Access Modifier

68

69


Download ppt "Chapter 11 -- Inheritance Jim Burns. The Concept of Inheritance Since day one, you have been creating classes and instantiating objects that are members."

Similar presentations


Ads by Google