CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer
This Lecture ’s topics Inheritance Concepts Inheritance Design – Inherited Members of a Class – Subclass Constructors – Overriding Inherited Methods 2
University Community Registry 3 Faculty Name Age ID Academic Dept. Courses taught Staff Name Age ID Office Graduate Student Name Age ID Major TA (Y/N) Degree (MS/PhD) Undergraduate Student Name Age ID Major Minor Dorm resident (Y/N)
University Community Registry 4 public class Faculty{ public String Name; public int age; public String ID; public String Academic Dept; public String [] Courses; //helper methods } public class Staff{ public String Name; public int age; public String ID; public String office; //helper methods } public class GradStudent{ public String Name; public int age; public int ID; public String Major; public String Degree; public boolean TA; //helper methods } public class UgStudent{ public String Name; public int age; public int IIT-ID; public String Major; public String minor; public boolean dorm-resident; //helper methods } Need to define and use a lot of classes! Can we do better? Using public class attributes is not good practice. I used here for simplification
University Community Registry 5 public class Faculty{ public String Name; public int age; public String ID; public String Academic Dept; public String [] Courses; //helper methods } public class Staff{ public String Name; public int age; public String ID; public String office; //helper methods } public class GradStudent{ public String Name; public int age; public int ID; public String Major; public String Degree; public boolean TA; //helper methods } public class UgStudent{ public String Name; public int age; public int IIT-ID; public String Major; public String minor; public boolean dorm-resident; //helper methods } These classes store some common information –i.e. have common attributes.
University Community Registry 6 public class CommunityMember{ public String Name; public int age; public String ID; } Wouldn’t it be great if we could reuse the code in class CommunityMember for the other classes such as Faculty, GradStudent, etc.? Classes Faculty, GradStudent, etc. are actually a specialization of the class CommunityMember
University Community Registry We can reuse code using a method called inheritance 7 public class CommunityMember{ public String Name; public int age; public String ID; } public class Faculty extends CommunityMember{ public String Academic Dept; public String [] Courses; //helper methods } public class Staff extends CommunityMember{ public String office; //helper methods } Use the keyword “extends” for inheriting the code from class CommunityMember
University Community Registry Depending on the accessmodifiers, subclass can access the attributes and methods of superclass 8 class CommunityMember{ public String Name; public int age; public String ID; } class Faculty extends CommunityMember{ public String Academic Dept; public String [] Courses; public printAge(){ System.out.println(“Age: ” + this.age); } Access the “age” attribute defined for CommunityMember class
University Community Registry 9 public class CommunityMember{ public String Name; public int age; public String ID; } public class Faculty extends CommunityMember{ public String Academic Dept; public String [] Courses; //helper methods } Since Faculty inherits or reuses the code from CommunityMember, Faculty is called the subclass of CommunityMember Since CommunityMember provides attributes and methods for Faculty, CommunityMember is called the superclass of CommunityMember
University Community Registry 10 public class GradStudent{ public String Name; public int age; public int ID; public String Major; public String Degree; public boolean TA; //helper methods } public class UgStudent{ public String Name; public int age; public int IIT-ID; public String Major; public String minor; public boolean dorm-resident; //helper methods } Inherit from class CommunityMember public class CommunityMember{ public String Name; public int age; public String ID; } public class Student extends CommunityMember{ public String Major; }
University Community Registry 11 public class CommunityMember{ public String Name; public int age; public String ID; } public class Student extends CommunityMember{ public String Major; } public class GradStudent extends Student{ public String Degree; public boolean TA; //helper methods } public class UgStudent extends Student{ public String minor; public boolean dorm-resident; //helper methods }
Specifying Inheritance The syntax for defining a subclass is to use the extends keyword in the class header, as in: accessModifier class SubclassName extends SuperclassName { // class definition } The superclass name specified after the extends keyword is called the direct superclass As mentioned, a subclass can have many superclasses, but only one direct superclass 12
Inheritance Concepts A common form of reuse of classes is inheritance We can organize classes into hierarchies of functionality The class at the top of the hierarchy (superclass) defines instance variables and methods common to all classes in the hierarchy We derive a subclass, which inherits behavior and fields from the superclass 13
What is the Advantage? If Class B inherits Class A then: – All the methods that class A has are also members of Class B. – All public instance variables of Class A are also members of Class B. – That means that Class B can use these public members of Class A without using an object of Class A to invoke them. In this example Class A is called the SUPERCLASS and Class B is called the SUBCLASS 14
Direct Superclass Class C Class A Class B Class B is the Direct Superclass Class A inherits from Class B but it also inherits indirectly Class C. 15
Superclasses and Subclasses A superclass can have multiple subclasses Subclasses can be superclasses of other subclasses A subclass can inherit directly from only one superclass- – Multiple inheritance is not allowed in Java (C++ allows multiple inheritance). All classes inherit from the Object class 16
Multiple Inheritance The concept of multiple inheritance is shown below (even though Java does not allow it). Class AClass BClass C Class D 17
Multiple Inheritance In the examples thus far we used Single Inheritance: – That means that a subclass can only inherit from a one superclass. Multiple Inheritance means that a subclass can inherit from more than one superclass. – Some languages allow that (i.e. C++). – Java DOES Not allow it. 18
A Sample Vehicle Hierarchy This hierarchy is depicted using a Unified Modeling Language (UML) diagram. In UML diagrams, arrows point from the subclass to the superclass. 19
Superclasses and Subclasses A big advantage of inheritance is that we can write code that is common to multiple classes once and reuse it in subclasses A subclass can define new methods and instance variables, some of which may override (hide) those of a superclass Remember that the subclass gets to use the methods of its superclass as if they were its own (just call them without using an object to invoke them) 20
When Do We have Inheritance? We have inheritance if a “is a” relationship exists between classes. For instance, assume that we have the class Auto. If we were to create a new class called SUV then we can say that SUV is an Auto. Therefore our new class SUV could inherit the class Auto. 21
Inheritance Rules (public) Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass? public fieldsyesyes, by using field name yes public methodsyesyes, by calling method from subclass methods yes 22
Inheritance Rules (private) Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass? private fieldsnono, must call public accessors and mutators private methodsno 23 Super class members declared as private are not inherited, although they are part of the subclass.
Inheritance Rules (protected) Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass? protected fieldsyesyes, by using field name no, must call accessors and mutators protected methods yesyes, by calling method from subclass methods no 24 protected members are inherited by subclasses (like public members), while still being hidden from client classes (like private members). Also, any class in the same package as the superclass can directly access a protected field, even if that class is not a subclass.
protected Members Disadvantage: – Because more than one class can directly access a protected field, protected access compromises encapsulation and complicates maintenance. – For that reason, we prefer to use private, rather than protected, for our instance variables. 25
Inheritance Rules for Constructors Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass Using a Subclass Reference? constructorsnoyes, using super( arg list ) in a subclass constructor no 26
Subclass Constructors Constructors are not inherited. However, the subclass can call the constructors of the superclass to initialize inherited fields. Implicit invocation – The default constructor of the subclass automatically calls the default constructor of the superclass. For explicit invocation, use this syntax: super( argument list ); If used, this statement must be the first statement in the subclass constructor. 27
Overriding Inherited Methods A subclass can override (or replace) an inherited method by providing a new version of the method. The signature of the new version must match the inherited method. When the client calls the method, it will call the subclass version. The superclass method is invisible to the client of the subclass, but the subclass methods can still call the superclass method using this syntax: super.methodName( argument list ) 28
Do not confuse overriding a method with overloading a method. Overriding a method: – A subclass provides a new version of that method (same signature), which hides the superclass version from the client. Overloading a method: – A class provides a version of the method, which varies in the number and/or type of parameters (different signature). A client of the class can call any of the public versions of overloaded methods. Common Error Trap 29
The Bank Account Example 30 Note 1: + indicates public and – indicates private Note 2: return types Are shown after the Name and arguments listing of a method Remember, all classes inherit the object class See Example 10.1 BankAccount.java
The BankAccount Class The BankAccount class is the superclass. – Instance variables: balance (double) MONEY (a constant DecimalFormat object) – Methods: Default and overloaded constructors deposit and withdraw methods balance accessor toString See Example 10.1 BankAccount.java 31
The CheckingAccount Class We derive the CheckingAccount subclass from BankAccount: public class CheckingAccount extends BankAccount { } A subclass inherits the public members of a superclass (except constructors). Thus, the CheckingAccount class inherits – the MONEY instance variable – The getBalance, deposit, withdraw, and toString methods See Example 10.2 CheckingAccount.java and Example 10.3 CheckingAccountClient.java 32
private Members Thus, a balance instance variable is allocated to all CheckingAccount objects, but methods of the CheckingAccount class cannot directly access balance. To set or get the value of balance, the CheckingAccount methods must call the withdraw, deposit, or getBalance methods. This simplifies maintenance because the BankAccount class enforces the data validation rules for balance. 33
CheckingAccount Constructors public CheckingAccount( ) { // optional explicit call // to BankAccount default constructor super( ); } public CheckingAccount( double startBalance ) { // explicit call to BankAccount // overloaded constructor super( startBalance ); } See Examples 10.4, 10.5, and
Common Error Trap An attempt by a subclass to directly access a private field or call a private method defined in a superclass will generate a compiler error. – To set initial values for private variables, call the appropriate constructor of the direct superclass. For example, this statement in the overloaded CheckingAccount class constructor calls the overloaded constructor of the BankAccount class: super( startBalance ); 35
SOFTWARE ENGINEERING TIP Overloaded constructors (same as non default constructors) in a subclass should explicitly call the direct super class constructor to initialize the fields in its super classes. 36
The BankAccount Heirarchy 37 Note 1: + indicates public and – indicates private Note 2: return types Are shown after the Name and arguments listing of a method
Adding Specialization A subclass can define new fields and methods that the superclass does not have. That is called specialization. Our CheckingAccount class adds – these instance variables: monthlyFee, a double DEFAULT_FEE, a double constant – these methods: setMonthlyFee, the accessor getMonthlyFee, the mutator applyMonthlyFee, which charges the monthly fee to the account 38