Learning Objectives
After completing this session, you will be able to:
Define Inheritance
Explain the need of Inheritance
Identify how to derive a subclass
Define Object class
Explain constructor calling chain
Identify “super” keyword
Override methods
Hide methods and fields
Apply type casting
Write final class and final methods Inheritance
Inheritance is the concept of a child class (sub class) automatically inheriting the variables and methods defined in its parent class (super class).
The primary features of object-oriented programming are encapsulation and polymorphism.
Importance of Inheritance
The benefit of inheritance in OOP is reusability. Once a behavior (method) is defined in a super class, that behavior is automatically inherited by all subclasses
Thus, you write a method only once and it can be used by all subclasses:
Once a set of properties (fields) are defined in a super class, the same set of
properties are inherited by all subclasses. A class and its children share common set of properties
A subclass only needs to implement the differences between itself and the parent.
Deriving a Subclass
To derive a child class, you use the extends keyword.
Suppose you have a parent class called Person.
public class Person { protected String name;
protected String address;
/**
* Default constructor */
public Person(){
System.out.println(“Inside Person:Constructor”);
name = ""; address = "";
}
. . . . }
extends Keyword
Now, you want to create another class named Student.
Since a student is also a person, you decide to just extend the class Person, so that you can inherit all the properties and methods of the existing class Person.
To do this, you write,
public class Student extends Person { public Student(){
System.out.println(“Inside Student:Constructor”);
}
. . . . }
What you can do in a Subclass
A subclass inherits all of the “public” and “protected” members (fields or methods) of its parent, no matter what package the subclass is in.
If the subclass is in the same package as its parent, then it also inherits the package-private members (fields or methods) of the parent.
What you can do in a Sub-class Regarding Fields
The inherited fields can be used directly, just like any other fields.
You can declare new fields in the subclass that are not in the super class.
You can declare a field in the subclass with the same name as the one in the super class, thus hiding it (not recommended).
A subclass does not inherit the private members of its parent class. However, if the super class has public or protected methods for accessing its private fields, these can also be applied by the subclass.
What you can do in a Sub-class Regarding Methods
The inherited methods can be used directly as they are.
You can write a new instance method in the subclass that has the same signature as the one in the super class, thus overriding it.
You can write a new static method in the subclass that has the same signature as the one in the super class, thus hiding it.
You can declare new methods in the subclass that are not in the super class.
Object Class
Object class is mother of all classes.
In Java language, all classes are subclassed (extended) from the Object super class.
Object class is the only class that does not have a parent class
Object class defines and implements behavior common to all classes including the ones that you write.
Following are some of the important methods of the Object class:
getClass()
equals()
toString()
Class Hierarchy
A sample class hierarchy is shown in the following figure:
Superclass and Subclass
Superclass (Parent class) : Any class preceding a specific class in the class hierarchy
Sub class (Child class) : Any class following a specific class in the class hierarchy
How Constructor Method of a Super Class gets Called
A subclass constructor invokes the constructor of the superclass implicitly. When a Student object, a subclass (child class), is instantiated, the default constructor of its super class (parent class), Person class, is invoked implicitly before the constructor method of the subclass is invoked.
A subclass constructor can invoke the constructor of the super explicitly by using the
“super” keyword:
The constructor of the Student class can explicitly invoke the constructor of the Person class using “super” keyword
Used when passing parameters to the constructor of the super class
Example: Constructor Calling Chain To illustrate this, consider the following code:
public static void main( String[] args ){
Student anna = new Student();
}
In the code, you create an object of class Student.
The output of the program is:
Inside Person:Constructor Inside Student:Constructor
Example: Constructor Calling Chain The program flow is shown in the following figure:
The “super” Keyword
A subclass can also explicitly call a constructor of its immediate super class.
This is done by using the super constructor call.
A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the super class, based on the arguments passed.
For example, in your preceding example classes Person and Student, you show an example of a super constructor call.
In the given the following code for Student:
public Student(){
super( "SomeName", "SomeAddress" );
System.out.println("Inside Student:Constructor");
}
Few things to remember when using the super constructor call:
The super() call must occur as the first statement in a constructor.
The super() call can only be used in a constructor (not in ordinary methods).
Another use of super is to refer to members of the super class (just like the this reference ).
For example:
If a derived class needs to have a different implementation of a certain instance method from that of the super class, then override that instance method in the sub class:
Note that the scheme of overriding applies only to instance methods.
For static methods, it is called hiding methods.
The overriding method has the same name, number and type of parameters, and return type as the method it overrides.
The overriding method can also return a subtype of the type returned by the overridden method This is called a covariant return type.
Example: Overriding Methods
Suppose you have the following implementation for the getName method in the Person super class:
public class Person { :
:
public String getName(){
System.out.println("Parent: getName");
return name;
} }
To override the getName() method of the superclass Person in the subclass Student, reimplement the method with the same signature.
public class Student extends Person{
:
public String getName(){
System.out.println("Student: getName");
return name;
} : }
Now, when you invoke the getName() method of an object of the subclass Student, the getName() method of the Student class would be called, and the output would be:
Student: getName
Modifiers in the Overriding Methods
The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the super class can be made public, but not private, in the subclass.
You will get a compile-time error if you attempt to change an instance method in the super class to a class method in the subclass, or change the class method to an instance method in the super class.
Run-time Polymorphism with Overriding Methods Polymorphism in a Java program means:
The ability of a reference variable to change behavior according to what object instance it is holding
This allows multiple objects of different subclasses to be treated as objects of a single super class, while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to
Example: Run-time Polymorphism Code:
Person person2 = new Student();
person2.myMethod("test4");
Person person3 = new InternationalStudent();
person3.myMethod("test5");
Result:
myMethod(test4) in Student class is called
myMethod(test5) in InternationalStudent class is called.
Hiding Methods
If a subclass defines a class method (static method) with the same signature as a class method in the super class, then the method in the subclass “hides” the one in the super class.
Example: Coding of Hiding Static Method class Animal {
public static void testClassMethod() {
System.out.println("The class method in Animal.");
} }
// The testClassMethod() of the child class hides the one of // the super class – it looks like overriding, doesn't it?
class Cat extends Animal {
public static void testClassMethod() {
System.out.println("The class method in Cat.");
} }
Overriding Method Versus Hiding Method
Hiding a static method of a super class looks like overriding an instance method of a super class.
The difference comes during run time:
When you override an instance method, you get the benefit of run-time polymorphism.
When you override a static method, there is no runt-time polymorphism.
Example: Overriding Method Versus Hiding Method During Runtime // Create object instance of Cat.
Cat myCat = new Cat();
// The object instance is Cat type
// and assigned to Animal type variable.
Animal myAnimal2 = myCat;
// For static method, the static method of // the super class gets called.
Animal.testClassMethod();
// For instance method, the instance method // of the subclass is called even though // myAnimal2 is a super class type. This is // run-time polymorphism.
myAnimal2.testInstanceMethod();
Hiding Fields
Within a sub class, a field that has the same name as a field in the super class, hides the super class' field, even if their types are different.
Within the subclass, the field in the super class cannot be referenced by its simple name, instead, the field must be accessed through super keyword.
Generally speaking, hiding fields is not a recommended programming practice as it makes code difficult to read.
Try It Out
Problem Statement:
Write a program that illustrate the use of ‘this’ and ‘super’.
Code:
class ThisSuper extends SuperClass { String s = "this";
public static void main(String[] args) {
new ThisSuper();
void display(String s) {
System.out.println("this: " + s);
} }
Refer Files: ThisSuper.java, SuperClass.java to obtain soft copy of the program code
How It Works:
The ThisSuper class extends SuperClass. Both ThisSuper and SuperClass define the s member variable and display() method. The ThisSuper s variable hides the
SuperClass s variable and the ThisSuper display() method overrides the SuperClass display method.
The ThisSuper constructor uses this and super like the following:
display(this.s);
display(super.s);
this.display(s);
super.display(s);
These statements produce the following output:
this: this this: super this: this super: this
The first three statements use the display() method of ThisSuper to display the s member variable.
The first and third statements refer to the current (ThisSuper) object instance.
The second statement uses super to refer to the s variable of SuperClass.
The last statement uses super to refer to the display() method and s variable of ThisSuper.
Tips and Tricks:
What is the purpose of using Object class?
What if you make a concrete subclass and you need to override a method, but you want the behavior in the superclass version of the method?
Why would anyone want to make a class final? Does not that defeat the whole purpose of object orientation?
Solution:
The Object class serves two main purposes, namely to act as a polymorphic type for methods that need to work on any class that you or anyone else makes, and to provide real method code that all objects in Java need at run time. Some of the most important methods in Object are related to threads.
One area of good object oriented design looks at how to design concrete code that is meant to be overridden. The keyword super lets you to invoke a superclass version of an overridden method, from within the subclass.
A typical reason for making a class final is for security. You cannot, for example make a subclass of the String class. Imagine the havoc if someone extended the String class and substituted their own String subclass objects, polymorphically, where String objects are expected.
Summary
Abstract methods must be overridden by the first concrete (non-abstract) subclass.
With respect to the method that it overrides, the overriding method
Must have the same argument list.
Must have the same return type, except that as of Java 5, the return type can be a subclass – this is known as covariant return.
Must not have a more restrictive access modifier.
May have a less restrictive access modifier.
Must not throw new or broader checked exceptions.
May throw fewer or narrower checked exceptions, or any unchecked exception.
final methods cannot be overridden.
A subclass uses super.overriddenMetodName() to call the superclass version of an overridden method.
Polymorphism applies to overriding, not to overloading.
Object type (not the reference variable’s type), determines which overridden method is used at runtime.
Test Your Understanding
1. Which one of the following statements regarding derived subclasses is not correct?
a) A derived class inherits both the variables and the methods in the base class.
b) A derived class can inherit from two or more base classes.
c) A derived class can implement two or more interfaces.
d) A derived class can act as a base class for another derived class.
2. What is the usage of the keyword ‘super’?
3. Differentiate between overriding and overloading a method.
Session 46: Inheritance, Interfaces and Abstract Classes
Learning Objectives
After completing this session, you will be able to:
Define abstract method and an abstract class
Define an interface
Explain the importance of interface
Identify interface as a type
Differentiate between interface and class
Implement an interface
Implementing multiple interfaces
Identify inheritance among interfaces
Describe interface and polymorphism
Rewrite an interface Abstract Methods
Methods that do not have implementation (body) are called abstract methods
To create an abstract method, just write the method declaration without the body and use the keyword abstract
No { } Please make this point that there are no parentheses will be available.
For example,
// Note that there is no body public abstract void someMethod();
Abstract Class
An abstract class is a class that contains one or more abstract methods.
An abstract class cannot be instantiated.
You will get a compile error on the following code
MyAbstractClass a1 = new MyAbstractClass();
Another class (Concrete class) has to provide implementation of abstract methods:
Concrete class has to implement all abstract methods of the abstract class in order to be used for instantiation
Concrete class uses extends keyword Sample Abstract Class
public abstract class LivingThing { public void breath(){
System.out.println("Living Thing breathing...");
}
public void eat(){
System.out.println("Living Thing eating...");
}
Extending An Abstract Class
When a concrete class extends the LivingThing abstract class, it must implement the abstract method walk() , or else, that subclass will also become an abstract class, and therefore cannot be instantiated.
For example,
public class Human extends LivingThing { public void walk(){
System.out.println("Human walks...");
} }
When to use Abstract Methods and Abstract Class
Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations. These subclasses extend the same abstract class and provide different implementations for the abstract methods.
Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class.
What is an Interface?
It defines a standard and public way of specifying the behavior of classes: Defines a contract
All methods of an interface are abstract methods: Defines the signatures of a set of methods, without the body (implementation of the methods)
A concrete class must implement the interface (all the abstract methods of the Interface)
It allows classes, regardless of their locations in the class hierarchy, to implement common behaviours
Example 1: Interface
// Note that Interface contains just set of method // signatures without any implementations.
// No need to say abstract modifier for each method // since it assumed.
public interface Relation {
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Example 2: OperatorCar Interface public interface OperateCar {
// constant declarations, if any // method signatures
int turn(Direction direction,
double radius, double startSpeed, double endSpeed);
int changeLanes(Direction direction, double startSpeed, double endSpeed);
int signalTurn(Direction direction, boolean signalOn);
int getRadarFront(double distanceToCar, double speedOfCar);
int getRadarRear(double distanceToCar, double speedOfCar);
...
// more method signatures }
Why do you use Interfaces? Reason #1
To reveal the programming interface of an object (functionality of the object) without revealing its implementation:
This is the concept of encapsulation
The implementation can change without affecting the caller of the interface
The caller does not need the implementation at the compile time:
It needs only the interface at the compile time
During runtime, actual object instance is associated with the interface type Why do you use Interfaces? Reason #2
To have unrelated classes implement similar methods (behaviors): One class is not a sub-class of another
Example:
Class Line and class MyInteger
They are not related through inheritance
You want both to implement comparison methods checkIsGreater(Object x, Object y) checkIsLess(Object x, Object y) checkIsEqual(Object x, Object y)
Define Comparison interface, which has the three earlier abstract methods
Why do you use Interfaces? Reason #3
To model multiple inheritance: A class can implement multiple interfaces while it can extend only one class
Interface versus Abstract Class
All methods of an interface are abstract methods while some methods of an abstract class are abstract methods. Abstract methods of abstract class have abstract modifier
An interface can only define constants while abstract class can have fields.
Interfaces have no direct inherited relationship with any particular class, they are defined independently. Interfaces themselves have inheritance relationship among themselves.
Interface as a Type
When you define a new interface, you are defining a new reference type.
If you define a reference variable whose type is an interface, then any object you assign to it must be an instance of a class that implements the interface.
Example: Interface as a Type
Person class implements PersonInterface interface.
You can do:
Person p1 = new Person();
PersonInterface pi1 = p1;
PersonInterface pi2 = new Person();
Interface versus Class: Commonality
Interfaces and classes are both types: This means that an interface can be used in places where a class can be used.
For example:
// Recommended practice
PersonInterface pi = new Person();
// Not recommended practice Person pc = new Person();
Interface versus Class: Differences
The methods of an interface are all abstract methods. They cannot have bodies. You cannot create an instance from an interface.
For example:
PersonInterface pi = new PersonInterface(); //ERROR!
An interface can only be implemented by classes or extended by other interfaces.
Defining Interface
To define an interface, you write:
public interface [InterfaceName] { //some methods without the body }
As an example, create an interface that defines relationships between two objects according to the
“natural order” of the objects.
public interface Relation {
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Implementing Interfaces
To create a concrete class that implements an interface, use the implements keyword.
/**
* Line class implements Relation interface */
public class Line implements Relation { private double x1;
private double x2;
private double y1;
private double y2;
public Line(double x1, double x2, double y1, double y2){
this.x1 = x1;
}
public boolean isGreater( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen > bLen);
}
public boolean isLess( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen < bLen);
}
public boolean isEqual( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen == bLen);
} }
When your class tries to implement an interface, always make sure that you
implement all the methods of that interface, or else, you would encounter the following error:
Line.java:4: Line is not abstract and does not override abstract method isGreater(java.lang.Object,java.lang.Object) in Relation
public class Line implements Relation
^
1 error
Implementing Class
Implementing class can have its own methods.
Implementing class extend a single super class or abstract class.
Relationship of an Interface to a Class
A concrete class can only extend one super class, but it can implement multiple Interfaces. The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative.
A concrete class can only extend one super class, but it can implement multiple Interfaces. The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative.