Download Object-Oriented Programming: Constructor Chaining and Inheritance in Java and more Slides Object Oriented Programming in PDF only on Docsity!
CS211, Fall, 1999. KAM OOP.fm 1/
Object-oriented Programming
Reference:
Chapter 6 of A Programmer’s Guide to Java Certification: A Comprehensive Primer.
Overview
- The inheritance relationship: is-a
- The aggregation relationship: has-a
- Overridden and overloaded methods
- The keyword super
- Variable shadowing
- Constructors and constructor chaining using this() and super()
- Single implementation inheritance, multiple interface inheritance
and supertypes
- Assigning, casting and passing references
- The instanceof operator
- Polymorphism and dynamic method lookup
- Encapsulation
- Choosing between inheritance and aggregation
CS211, Fall, 1999. KAM Object-oriented Programming 3/
Extensibility by Linear Implementation Inheritance
- One fundamental mechanism for code reuse.
- The new class inherits all the members of the old class - not to be confused with
accessibility of superclass members.
- A class in Java can only extend one other class, i.e. it can only have one immediate
superclass.
- The superclass is specified using the extends clause in the header of the subclass.
- The definition of the subclass only specifies the additional new and modified mem-
bers in its class definition.
- All classes extend the java.lang.Object class.
Example 1 Extending Classes
class Light { // (1) // Instance variables private int noOfWatts; // wattage private boolean indicator; // on or off private String location; // placement // Static variable private static int counter; // no. of Light objects created // Constructor Light() { noOfWatts = 50; indicator = true; location = new String("X"); } // Instance methods public void switchOn() { indicator = true; } public void switchOff() { indicator = false; } public boolean isOn() { return indicator; } // Static methods public static void writeCount() { System.out.println("Number of lights: " + counter); } //... }
CS211, Fall, 1999. KAM Object-oriented Programming 7/
Figure 1 Inheritance Hierarchy
Light
java.lang.Object
LightBulb TubeLight
SpotLightBulb NeonLight
Implications of Inheritance
- An object of a subclass can be used wherever an object of the superclass can be used.
- An object of the TubeLight class can be used wherever an object of the superclass
Light can be used.
- An object of the TubeLight class is-a object of the superclass Light.
- The inheritance relationship is transitive : if class B extends class A, then a class C,
which extends class B, will also inherit from class A via class B.
- An object of the SpotLightBulb class is-a object of the class Light.
- The is-a relationship does not hold between peer classes: an object of the LightBulb
class is not an object of the class TubeLight, and vice versa.
- Litmus test for using inheritance : if B is an A, then only let B inherit from A.
i.e. do not use inheritance unless all inherited behavior makes sense.
CS211, Fall, 1999. KAM Object-oriented Programming 9/
Aggregation
- A major mechanism for code reuse mechanism is aggregation.
- Aggregation defines the relationship has-a (a.k.a. whole–part relationship)
between an instance of a class and its constituents (a.k.a. parts).
- In Java, an aggregate object cannot contain other objects.
- It can only have references to its constituent objects.
- The has-a relationship defines an aggregation hierarchy.
- In this simple form of aggregation, constituent objects can be shared between
objects, and their lifetimes are independent of the lifetime of the aggregate object.
Illustrating Inheritance
Figure 2 Inheritance Relationship between String and Object classes
java.lang.Object
equals() getClass() notify() ...
java.lang.String
equals() substring() length() ...
CS211, Fall, 1999. KAM Object-oriented Programming 13/
Method Overriding
- The equals() method is redefined in the String class with the same signature (i.e.
method name and parameters) and the same return type.
System.out.println("(6): " + objRef.equals("Java")); // (6)
- The compiler can check that the Object class does define a method called equals().
Polymorphism and Dynamic Method Binding
- The ability of a superclass reference to denote objects of its own class and its sub-
classes at runtime is called polymorphism.
- The method invoked is dependent on the actual (type of) object denoted by the ref-
erence at runtime.
- The actual method is determined by dynamic method lookup.
System.out.println("(6): " + objRef.equals("Java")); // (6) System.out.println("(7): " + objRef.getClass()); // (7)
- At (6), dynamic method lookup results in the equals() method from the String class
being executed, and not the one in the Object class.
- At (7), dynamic method lookup determines that the method getClass() inherited
from the Object class to be executed - leading to a "search" up the inheritance hier-
archy.
Downcasting
- Casting the value of a superclass reference to a subclass type is called downcasting ,
and requires explicit casting.
stringRef = (String) objRef; // (8) System.out.println("(9): " + stringRef.equals("C++")); // (9)
- The cast can be invalid at runtime! - A ClassCastException would be thrown at runtime. - Use the instanceof operator to determine the runtime type of an object before
any cast is applied.
if (objRef instanceof String) { stringRef = (String) objRef; System.out.println("(9): " + stringRef.length); }
CS211, Fall, 1999. KAM Object-oriented Programming 15/
Sub is Sup
Sub
Sup
Sup a = b; // there b is Sub ref Sub b = (Sub) a;
if (a instanceof Sub) // there a is Sup ref
Method Overriding
- A subclass may override non-static methods (non-private and non-final) inherited
from the superclass.
- When the method is invoked on an object of the subclass, it is the new method
definition in the subclass that is executed.
- The new method definition in the subclass must have the same method signature
(i.e. method name and parameters) and the same return type.
- The new method definition, in addition, cannot “narrow” the accessibility of
the method, but it can “widen” it.
- The new method definition in the subclass can only specify all or a subset of
the exception classes (including their subclasses) specified in the throws clause
of the overridden method in the superclass.
- A subclass can also use the keyword super to invoke the overridden method in the
superclass.
- Any final, static and private methods in a class cannot be overridden but a sub-
class can redefine such methods although that would not be a good idea.
CS211, Fall, 1999. KAM Object-oriented Programming 19/
Output from the program:
Large bill: 500. Large bill: 500. Small bill: 50. Large bill Small bill Small bill No bill
Variable Shadowing
- A subclass cannot override variable members of the superclass, but it can shadow
them.
- A subclass method can use the keyword super to access inherited members,
including shadowed variables.
- When a method is invoked on an object using a reference, it is the class of the cur-
rent object denoted by the reference, not the type of the reference, that determines
which method implementation will be executed.
- When a variable of an object is accessed using a reference, it is the type of the refer-
ence , not the class of the current object denoted by the reference, that determines
which variable will actually be accessed.
CS211, Fall, 1999. KAM Object-oriented Programming 21/
Overriding vs. Overloading
- Method overriding requires the same method signature (name and parameters)
and the same return type, and that the original method is inherited from its super-
class.
- Overloading requires different method signatures, but the method name should
be the same.
- To overload methods, the parameters must differ in type or number.
- The return type is not a part of the signature, changing it is not enough to
overload methods.
- A method can be overloaded in the class it is defined in, or in a subclass of its
class.
- Invoking an overridden method in the superclass from a subclass requires special
syntax (for example, the keyword super).
Object Reference super
- The this reference is passed as an implicit parameter when an instance method is
invoked.
- It denotes the object on which the method is called.
- The keyword super can be used in the body of an instance method in a subclass to
access variables and invoke methods inherited from the superclass.
- The keyword super provides a reference to the current object as an instance of
its superclass.
- The super.super.X construct is invalid.
CS211, Fall, 1999. KAM Object-oriented Programming 25/
public class Client { public static void main(String args[]) throws InvalidHoursException { NeonLight neonRef = new NeonLight(); neonRef.demonstrate(); } }
Output from the program:
Let there be light! Large bill: 2000. No bill Large bill Large bill: 2000. Small bill
Constructor Overloading
- Constructors cannot be inherited or overridden.
- They can be overloaded, but only in the same class.
class Light { // Instance Variables private int noOfWatts; // wattage private boolean indicator; // on or off private String location; // placement // Constructors Light() { // (1) Explicit default constructor noOfWatts = 0; indicator = false; location = "X"; System.out.println("Returning from default constructor no. 1."); } Light(int watts, boolean onOffState) { // (2) Non-default noOfWatts = watts; indicator = onOffState; location = "X"; System.out.println("Returning from non-default constructor no. 2."); }
CS211, Fall, 1999. KAM Object-oriented Programming 27/
Light(int noOfWatts, boolean indicator, String location) { // (3) Non-default this.noOfWatts = noOfWatts; this.indicator = indicator; this.location = new String(location); System.out.println("Returning from non-default constructor no. 3."); } } public class DemoConstructorCall { public static void main(String args[]) { // (4) System.out.println("Creating Light object no.1."); Light light1 = new Light(); System.out.println("Creating Light object no.2."); Light light2 = new Light(250, true); System.out.println("Creating Light object no.3."); Light light3 = new Light(250, true, "attic"); } }
Output from the program:
Creating Light object no.1. Returning from default constructor no. 1. Creating Light object no.2. Returning from non-default constructor no. 2. Creating Light object no.3. Returning from non-default constructor no. 3.
this() Constructor Call
- The this() construct can be regarded as being “locally overloaded”.
- The this() call invokes the constructor with the corresponding parameter list.
- Local chaining of constructors in the class when an instance of the class is created.
- Java specifies that when using the this() call, it must occur as the first statement
in a constructor, and it can only be used in a constructor definition.
- Note the order in which the constructors are invoked in the example.
CS211, Fall, 1999. KAM Object-oriented Programming 31/
super() Constructor Call
- The super() construct is used in a subclass constructor to invoke constructors in
the immediate superclass.
- This allows the subclass to influence the initialization of its inherited state when
an object of the subclass is created.
- A super() call in the constructor of a subclass will result in the execution of the rel-
evant constructor from the superclass, based on the arguments passed.
- The super() call must occur as the first statement in a constructor, and it can only
be used in a constructor definition.
- This implies that this() and super() calls cannot both occur in the same con-
structor.
Example 6 super() Constructor Call
class Light { // Instance Variables private int noOfWatts; private boolean indicator; private String location; // Constructors Light() { // (1) Explicit default constructor this(0, false); System.out.println( "Returning from default constructor no. 1 in class Light"); } Light(int watt, boolean ind) { // (2) Non-default this(watt, ind, "X"); System.out.println( "Returning from non-default constructor no. 2 in class Light"); } Light(int noOfWatts, boolean indicator, String location) { // (3) Non-default super(); // (4) this.noOfWatts = noOfWatts; this.indicator = indicator; this.location = new String(location); System.out.println( "Returning from non-default constructor no. 3 in class Light"); } }
CS211, Fall, 1999. KAM Object-oriented Programming 33/
class TubeLight extends Light { // Instance variables private int tubeLength; private int colorNo; TubeLight(int tubeLength, int colorNo) { // (5) Non-default this(tubeLength, colorNo, 100, true, "Unknown"); System.out.println( "Returning from non-default constructor no. 1 in class TubeLight"); } TubeLight(int tubeLength, int colorNo, int noOfWatts, boolean indicator, String location) { // (6) Non-default super(noOfWatts, indicator, location); // (7) this.tubeLength = tubeLength; this.colorNo = colorNo; System.out.println( "Returning from non-default constructor no. 2 in class TubeLight"); } } public class Chaining { public static void main(String args[]) { System.out.println("Creating a TubeLight object."); TubeLight tubeLightRef = new TubeLight(20, 5); // (8) } }
Output from the program:
Creating a TubeLight object. Returning from non-default constructor no. 3 in class Light Returning from non-default constructor no. 2 in class TubeLight Returning from non-default constructor no. 1 in class TubeLight
CS211, Fall, 1999. KAM Object-oriented Programming 37/
- If a class only defines non-default constructors (i.e. only constructors with para-
meters), then its subclasses cannot rely on the implicit behavior of a super() call
being inserted.
- This will be flagged as a compile time error.
- The subclasses must then explicitly call a superclass constructor, using the
super() construct with the right arguments.
class NeonLight extends TubeLight { // Instance Variable String sign; NeonLight() { // (1) super(10, 2, 100, true, "Roof-top"); // (2) Cannot be commented out. sign = "All will be revealed!"; } // ... }
- Subclasses without any declared constructors will fail to compile if the superclass
does not have a default constructor and provides only non-default constructors.
Summary of super() Call Usage
Superclass No constructors or only the default constructor
Only non-default constructors Both default and non-default constructors
Subclass Default super() call or explicit default super() call
Explicit non-default super() call Default super() call or explicit default super() call or explicit non-default super() call
CS211, Fall, 1999. KAM Object-oriented Programming 39/
Interfaces
- Java provides interfaces which allow new type names to be introduced and used
polymorphically, and also permit multiple interface inheritance.
- Interfaces support programming by contract.
Defining Interfaces
- An interface defines a contract by specifying prototypes of methods, and not their
implementation.
{ }
- An interface is abstract by definition and therefore cannot be instantiated. It
should also not be declared abstract.
- Reference variables of the interface type can be declared.