CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism
Introduction to Inheritance
Introduction inheritance: an important and powerful object oriented technique that allows one to define new classes from existing classes. powerful feature for reusing software. defines an is-a relationship between two classes. Example: Suppose you want to define a class to model various shapes (Circles, Rectangles, Triangles, etc.). these classes could have many common features. design the classes to avoid redundancy between them.
Superclasses and Subclasses
Superclasses and Subclasses You can use a class to model objects of the same type. Even if classes are different, they can share common properties and behaviors these can be generalized in a class and then shared by other classes. Assume there are two classes C1 and C2 where C2 "extends" C1. in this case C1 is the superclass, parent class, or base class and C2 is the subclass, child class, extended class, or derived class A subclass inherits all accessible data fields and methods from its superclass, and can even add new data fields and methods.
A First Example Let's design a class to model geometric objects like circles and triangles. Geometric objects have many common properties and behaviors. GeometricObject Class: a general class that can be used to model all geometric objects. has properties color and filled and their getters / setters also has datecreated property and its getter also has a tostring() method to return a string representation of the object.
A First Example The Circle class: a special type of geometric object shares common properties and methods with other geometric objects define Circle to "extend" the GeometricObject class inherits everything from GeometricObject adds some of its own methods. The Rectangle Class: can also be defined as a subclass of GeometricObject inherits everything from GeometricObject adds some of its own methods.
A First Example
A First Example The Circle class uses the following syntax: extends is a keyword which tells the compiler that Circle is a subclass of GeometricObject, thus inheriting from the superclass. the constructor for Circle is implemented by invoking setcolor(), and setfilled() which reside in the parent class inherited by Circle. You may be tempted to do something like this: However, color and filled are private in the GeometricObject class and are only accessible in that class (so not accessible to Circle)
Notes on Inheritance Despite its naming, a subclass is not a subset of its superclass. Usually a subclass contains more information and methods than its superclass. Private data fields in the superclass are never accessible outside of the class. They cannot be used directly in a subclass. They can be accessed / mutated through public getters / setters if these are define in the superclass. Not all is-a relationships should be modeled using inheritance a square is a rectangle, but you should not extend Square from Rectangle width and height properties are not appropriate for a square better option is to define a Square class to extend GeomeotricObject and define a side property.
Notes on Inheritance Inheritance models the is-a relationship don't start extending classes willy-nilly just to reuse methods. it doesn't make sense for a Tree class to extend a Person class even if they share common properties like height and weight. subclasses and superclasses should always have the is-a relationship. Two things to ask for whether or not to use inheritance? do the two classes share common properties (data fields) and behaviors (methods)? does the is-a relationship make sense in the real world?
Notes on Inheritance Example 1: Tree extends Person do the two classes share something in common does the is-a relationship make sense? yes, they both have a height no, because a Tree is not a Person Example 2: Student extends Person do the two classes share something in common yes, they can have common properties does the is-a relationship make sense? yes, because a Student is-a Person
Notes on Inheritance Unlike other languages, Java does not allow you to have multiple inheritance inheriting from more than one class Java classes can only inherit directly from one superclass. (single inheritance) (we will come back to multiple inheritance when we talk about interfaces.)
Using the super Keyword
The super Keyword super is a keyword which refers to the superclass of the class in which super is used super can be used in two ways: call a superclass constructor. call a superclass method.
Calling Superclass Constructors Constructors are not inherited by a subclass and can only be invoked using the super keyword. Examples: super(); //call the no-arg super constructor super(parameters); //call the super constructor with the given parameters NOTE: the use of super to call the superclass constructor MUST be the first statement in the subclass constructor. invoking the superclass constructor with its class name in the subclass is a syntax error
Constructor Chaining A constructor can invoke an overloaded constructor or its superclass constructor. if neither is invoked explicitly, the compiler automatically puts super() as first statement in the constructor. Constructing an instance of a class invokes the constructors of all the superclasses along the inheritance chain. subclass constructors always invoke the superclass constructors before performing their own tasks even if there are multiple levels of inheritance
Constructor Chaining Example See Code: Faculty.java, Employee.java, and Person.java
Constructor Chaining Caution Classes should always define a no-arg constructor to avoid programming errors. Consider: Why does this cause compile errors?
Calling Superclass Methods super can be used to call other methods from the superclass. Syntax: super.method(parameters); printcircle() from the Circle class could be rewritten as follows:
Caution: No super.super.methodname() Assume there are three classes A, B, and C. Assume C inherits from B and B inherits from A A B C Assume A has a method mymethod() which is implemented in B and C Question: if you can use super.mymethod() in B to call A's version of mymethod(), can you also use super.super.mymethod() to call A's version of mymethod() in C? No, this is a syntax error. Only allowed one level of method chaining with super.
Overriding Methods
Overridding Methods override a method: when a subclass modifies the implementation of a method defined in the super class you have already seen this when you "override" the tostring() method. tostring() is defined in the Object class, and can be given a more specific implementation in any class in Java (since all classes are subclasses of Object).
Overridding Methods Rules for Overridding: instance methods can only be overridden if it is accessible (public). if a method defined in the subclass is private in the superclass, the two methods are unrelated. static methods can be inherited, but a static method cannot be overridden if a static method defined in the superclass is redefined in a subclass, the superclass version is "hidden". to access it you need to use SuperClassName.staticMethodName
Overriding Methods vs. Overloading Methods
Overriding vs. Overloading overloading: define multiple methods with the same name, but different method signatures. overloaded methods can be either in the same class or different classes related by inheritance overloaded methods have the same name but different parameter lists overridding: providing a completely new implementation for a method in a subclass. overridden methods are in different classes related by inheritance overridden methods have the exact same signature and return type.
Overriding vs Overloading
Override Annotation To avoid any confusion / mistakes, you can use a special Java syntax called the override annotation to indicate that a method is an override of another method. annotation is @Override and is placed before the method in the subclass. the annotation denotes that the annotated method is required to override a method in the superclass if the method with this annotation does not override it's superclass method, the compiler will report an error. Example: if tostring() is mistyped tostring() a compile error is reported if the annotation is present, no compile error reported if the annotation is omitted.
Override Annotation Example
Polymorphism
Polymorphism According to Liang, the three pillars of object-oriented programming are encapsulation, inheritance, and polymorphism. All classes define a type. lets define two terms: subtype: a type defined by a subclass supertype: a type defined by a superclass Example: We can say that Circle is a subtype of GeometricObject and GeometricObject is a supertype of Circle
Polymorphism Inheritance enables a subclass to inherit features from its superclass with additional new features A subclass is a specialization of its superclass every instance of a subclass is also an instance of its superclass, but the reverse is NOT true. Example: Every Circle is a GeometricObject, but not every GeometricObject is a Circle. Therefore: you can always pass an instance of a subclass, to a parameter of its superclass type polymorphism: a variable of a supertype can refer to a subtype object.
Dynamic Binding
Dynamic Binding dynamic binding: a method can be implemented in several classes along the inheritance chain, and the JVM decides which method to invoke at runtime. As we have already seen, a method can be defined in a superclass and overridden in its subclass. multiple versions of the same method exist along the inheritance chain.
Dynamic Binding Example: tostring() is defined in the Object class, and overridden in GeometricObject Consider: Which version of tostring() gets called here? The Object class's tostring()? The GeometricObject class's tostring()?
Dynamic Binding a variable must declare a type lets introduce two new terms: declared type: the type that declares a variable actual type: the actual class for the object referenced by the variable In the previous example: the declared type of o is Object because o is declared as Object o = the actual type of o is GeometricObject because the variable o references an object created using new GeometricObject()
Dynamic Binding So, to answer the original question, Which version of tostring() is called? Answer: the version invoked is always determined by the actual type of the reference variable Therefore: the GeometricObject version is invoked.
Dynamic Binding When does dynamic binding occur?: at runtime
Casting Objects and the instanceof Operator
Casting Objects and the instanceof Operator Remember casting? char ch = 'k'; int n = (int)ch; Well we can typecast an object reference into another type of object reference
Casting Objects and the instanceof Operator implicit object casting assigning a reference of a subtype, to a reference of the subtype's supertype. this is always allowed because a subtype is always an instance of its supertype...always. Example: GeometricObject go = new Circle();
Casting Objects and the instanceof Operator explicit object casting Example: is the following valid? GeometricObject go = new Circle(); Circle c = go; //no this causes a compile error Why doesn't this work? a Circle is always an instace of GeometricObject, but a GeometricObject is not necessarily an instance of Circle. Can we make this work?.. Yes GeometricObject go = new Circle(); Circle c = (Circle)go;
Casting Objects and the instanceof Operator For the casting to be successful, you MUST always make sure that the object to be cast is an instance of the subclass. If the superclass object is not an instance of the subclass a runtime ClassCastException occurs. Example: If GeometricObject was not an instance of Circle, then it cannot be case into a Circle.
Casting Objects and the instanceof Operator How can you verify that a class is an instance of some other class? the instanceof operator (NOTE: all lowercase) NOTE: all lowercase returns true if Class A is an instanceof Class B Example:
Casting Objects and the instanceof Operator Why is casting objects even necessary? Consider this: Circle is a subclass of GeometricObject Circle defines a getdiameter() method GeometricObject does not define a getdiameter() method. Would the following code be valid?: GeometricObject go = new Circle(); System.out.println(go.getDiameter());
Casting Objects and the instanceof Operator Other things to note:
The Object's equals method
The Object's equals method equals(object) is another method defined in the Object class. public boolean equals(object o) This method tests whether two objects are equal: object1.equals(object2)
The Object's equals method The default implementation: public boolean equals(object obj) { return (this == obj); } doesn't really do much for us only returns whether or not both objects reference the same area in memory Good practice dictates that you should always override this method and implement your own for every class you create which could be compared to other instances of the same class.
The Object's equals method Other Notes:
The protected Data and Methods
The protected Data and Methods Review: private: can be accessed only from inside of the class public: can be accessed from any other class What if you want to allow subclasses to access data fields or methods defined in the superclass directly, but prevent nonsubclasses from accessing these same data fields and methods Use the protected modifier
The protected Data and Methods Rules for Use: private: no modifiers (default): allow members of the class to be accessed directly from any class within the same package but not from other package. protected: hide the members of a class completely so they cannot be accessed directly from outside the class. use private for members which will not be used ANYWHERE outside the class enable the members of the class to be accessed by the subclasses in any package or classes in the same package use protected if they are intended for extenders of the class, but not any other users of the class. public: enable members of the class to be accessed by any class. use public if they are intended for users of the class
The protected Data and Methods Other Notes: private and protected can only be used for members of the class public and default (no modifier) can be used on members of the class as well as the class itself a class with no modifier (a non public class) is not accessible by classes from other packages
The protected Data and Methods
The protected Data and Methods
Preventing Extending and Overriding
Preventing Extending and Overriding A final class cannot be extended A final method cannot be overridden A final data field is a constant If you want to prevent a class from being extended (subclassed) or a method from being overridden by its subclasses you can use the final keyword. Examples: Math, String, StringBuilder, StringBuffer are all final, you cannot make subclasses from them
Preventing Extending and Overriding