1 / 69

Chapter 11 -- Inheritance

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.

pavel
Télécharger la présentation

Chapter 11 -- Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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. • 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 • It is a rectangle divided into three sections • the top section contains the name of the class • The middle section contains the names and data types of the attributes • The bottom section contains the methods

  4. The Employee class diagram

  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. • 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

  6. When you use inheritance you: • 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 • 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

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

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

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

  10. Extending Classes • You use the keyword extends to achieve inheritance in Java • 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

  11. Object instantiation • You instantiate an object with a statement such as • employeeWithTerritory northernRep = new EmployeeWithTerritory(); • 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

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

  13. After the northernRep object is declared… • Any of the following statements are appropriate northernRep.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

  14. Child classes are more specific • 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. • However, Orthodontist objects and Perodontist objects have access to the more general Dentist methods

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

  16. Overriding Superclass 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? • 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 • This is called polymorphism

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

  18. 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 use the method name with a child object, the child’s version of the method is used

  19. As an alternative… • 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. • 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.

  20. 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

  21. Understanding how Constructors are called During Inheritance • Consider the following: SomeClass anObject = new SomeClass(); • 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. • When a subclass constructor executes, the superclass constructor must execute first and then the subclass constructor

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

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

  24. 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; } }

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

  26. 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 write your own constructor, you replace the automatically supplied version

  27. More on constructors… • 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

  28. 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 • The format for the statement that calls a superclass constructor is • super(list of arguments);

  29. 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 you want the superclass method to be used, you use the keyword super to access the superclass method

  30. public class Customer { private int idNumber; private double balanceOwed; public Customer(int id, double bal) { idNumber = id; balanceOwed = bal; } public void display() { System.out.println("Customer #" + idNumber + " Balance $" + balanceOwed); } }

  31. public class PreferredCustomer extends Customer { double discountRate; public PreferredCustomer(int id, double bal, double rate) { super(id, bal); discountRate = rate; } public void display() { super.display(); System.out.println("Discount rate is " + discountRate); } }

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

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

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

  35. Learning about Information Hiding • 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

  36. public class Student { private int idNum; private double gpa; public int getIdNum; { return idNum; } public double getGpa() { return gpa; } public void setIdNum(int num) { idNum = num; } public void setGpa(double gradePoint) { gpa = gradePoint; } }

  37. Why won’t the following code work?? • 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: someStudent.setIdNum(812);

  38. Remember… • 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…. private

  39. This is called …. Information Hiding

  40. Are there other access modifiers?? • 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 • Then, you use the keyword protected

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

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

  43. public class BaseballPlayer { private int jerseyNumber; private double battingAvg; public static void printOrigins() { System.out.println("Abner Doubleday is often " + "credited with inventing baseball"); } }

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

  45. 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 • This doesn’t work even if you declare the method printOrigins() in the subclass ProfessionalBaseballPlayer to be static, as follows:

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

  47. However, the following code will work:

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

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

More Related