690 likes | 758 Views
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.
E N D
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. • Programmers use a graphical language to describe classes and object-oriented processes—this Unified Modeling Language consists of many types of diagrams
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
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
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
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
public class ASubClass extends ASuperClass { public ASubClass() { System.out.println("In subclass constructor"); } }
public class ASuperClass { public ASuperClass() { System.out.println("In superclass constructor"); } }
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
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
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();
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
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
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)…
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
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”);
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
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.
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
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
More… • Often the execution of the superclass constructor is transparent—nothing call attention to the fact that the superclass constructor is executing.
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???
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; } }
The above produces the following output at the Command Prompt C:\Java\java DemoConstructors In superclass constructor In subclass constructor
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
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
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);
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
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); } }
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); } }
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(); } }
Command Prompt • C:\Java>Java TestCustomers • Customer #124 Balance $123.46 • Chstomer #125 Balance $3456.78 • Discount rate is 0.15 • C:\Java>
public class DemoConstructors { public static void main(String[] args) { ASubClass child = new ASubClass(); } }
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
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; } }
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);
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
This is called …. Information Hiding
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
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
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
public class BaseballPlayer { private int jerseyNumber; private double battingAvg; public static void printOrigins() { System.out.println("Abner Doubleday is often " + "credited with inventing baseball"); } }
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"); } }
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:
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"); } }
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"); } }
When used with the following class: Public class TestProPlayer { public static void main(String[] args) { professionalBaseballPlayer aYankee = new ProfessionalBaseballPlayer(); aYankee.printOrigins(); } }