Session 10 - XP
Session 10 - XP
Describe inheritance
Explain the types of inheritance
Explain super class and subclass
Explain the use of super keyword
Explain method overriding
Describe Polymorphism
Differentiate type of reference and type of objects
Explain static and dynamic binding
Explain virtual method invocation
Explain the use of abstract keyword
For example, all four wheelers have wipers and a rear view mirror.
All vehicles have a vehicle number, wheels, and engine irrespective of a four-
wheeler or two-wheeler.
Following figure shows some examples of is-a relationship:
The class from which the subclass is derived is called a super class, base class, or parent class.
The derived class can reuse the fields and methods of the existing class without having to
re-write or debug the code again.
A subclass inherits all the members such as fields, nested classes, and methods from its super
class except those with private access specifier.
Constructors of a class are not considered as members of a class and are not inherited by
subclasses.
The child class can invoke the constructor of the super class from its own constructor.
Members having default accessibility in the super class are not inherited by subclasses of other
packages.
The subclass will have its own specific characteristics along with those inherited from the
super class.
Hierarchical Multiple
Inheritance Inheritance
• A parent class • A child class
has more than derives from
one child classes more than one
at different parent class
levels
where,
class1-name: Specifies the name of the child class.
class2-name: Specifies the name of the parent class.
Following code snippet demonstrates the creation of super class Vehicle:
package session10;
public class Vehicle {
if(powerSteer == true)
System.out.println(“Power Steering:Yes”);
else
System.out.println(“Power Steering:No”);
}
}
/**
* Define the TestVehicle.java class
*/
public class TestVehicle {
© Aptech Ltd. Inheritance and Polymorphism/Session 10 12
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
if(powerSteer==true){
System.out.println(“Power Steering:Yes”);
else
System.out.println(“Power Steering:No”);
}
/**
* Overridden method
* Accelerates the vehicle
*
* @return void
© Aptech Ltd. Inheritance and Polymorphism/Session 10 16
*/
@Override
public void accelerate(int speed) {
System.out.println(“Maximum acceleration:”+ speed + “ kmph”);
}
}
/**
* Define the TestVehicle.java class
*/
public class TestVehicle {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Create an object of child class and specify the values
FourWheeler objFour = new FourWheeler(“LA-09 CS-1406”, “Volkswagen”,
4, true);
objFour.showDetails(); // Invoke child class method
objFour.accelerate(200); // Invoke inherited method
}
}
© Aptech Ltd. Inheritance and Polymorphism/Session 10 17
The accelerate() method is overridden in the child class with the same signature
and return type but with a modified message.
Notice the use of @Override annotation on top of the method.
The accelerate() method now prints the message specified in the subclass.
Since the accelerate() method is overridden in the subclass, the subclass version
of the accelerate() method is invoked and not the super class accelerate()
method.
© Aptech Ltd. Inheritance and Polymorphism/Session 10 18
In the code, the subclass constructor is used to initialize the values of the common
attributes inherited from the super class Vehicle.
This is not the correct approach because all the subclasses of the Vehicle class will
have to initialize the values of common attributes every time in their constructors.
Java allows the subclass to invoke the super class constructor and methods using the
keyword super.
/**
* Parameterized constructor to initialize values based on user input
*
* @param vId a String variable storing vehicle ID
* @param vName a String variable storing vehicle name
* @param numWheels an integer variable storing number of wheels
*/
public Vehicle(String vId, String vName, int numWheels){
vehicleNo=vId;
vehicleName=vName;
wheels=numWheels;
}
Following code snippet depicts the modified subclass FourWheeler.java using the
super keyword to invoke super class constructor and methods:
package session10;
class FourWheeler extends Vehicle{
private boolean powerSteer; // Variable to store steering information
/**
* Parameterized constructor to initialize values based on user input
*
* @param vID a String variable storing vehicle ID
* @param vName a String variable storing vehicle name
* @param numWheels an integer variable storing number of wheels
© Aptech Ltd. Inheritance and Polymorphism/Session 10 21
* @param pSteer a String variable storing steering information
*/
public FourWheeler(String vId, String vName, int numWheels, boolean
pSteer){
// Invoke the super class constructor
super(vId,vName,numWheels);
powerSteer=pSteer;
}
/**
* Displays vehicle details
*
* @return void
*/
public void showDetails(){
System.out.println(“Vehicle no:”+ vehicleNo);
System.out.println(“Vehicle Name:”+ vehicleName);
System.out.println(“Number of Wheels:”+ wheels);
if(powerSteer==true){
System.out.println(“Power Steering:Yes”);
}
The super() method is used to call the super class constructor from the child class
constructor.
Similarly, the super.accelerate() statement is used to invoke the super class
accelerate() method from the child class.
Following figure shows the output of the code:
Thus, polymorph refers to an object that can have many different forms.
This principle can also be applied to subclasses of a class that can define their
own specific behaviors as well as derive some of the similar functionality of the
super class.
/**
* Overloaded method. Calculates commission based on overtime
* @param overtime an integer variable storing overtime hours
*
* @return void
*/
public void calcCommission(int overtime){
if(overtime > 8)
commission = salary/30;
else
commission = 0;
}
/**
* Displays employee details
*
* @return void
*/
© Aptech Ltd. Inheritance and Polymorphism/Session 10 28
public void displayDetails(){
System.out.println(“Employee ID:”+empId);
System.out.println(“Employee Name:”+empName);
System.out.println(“Salary:”+salary);
System.out.println(“Commission:”+commission);
}
}
/**
* Define the EmployeeDetails.java class
*/
public class EmployeeDetails {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
// Instantiate the Employee class object
Employee objEmp = new Employee(“E001”,”Maria Nemeth”, 40000);
// Invoke the calcCommission() with float argument
objEmp.calcCommission(20000F);
objEmp.displayDetails(); // Print the employee details
} }
© Aptech Ltd. Inheritance and Polymorphism/Session 10 29
In the example, when the calcCommission() method is executed, the method
with float argument gets invoked because it was bounded during compile time
based on the type of variable, that is, float.
Following figure shows the output of the code:
/**
* Parameterized constructor to initialize values based on user input
*
* @param id a String variable storing employee ID
* @param name a String variable storing employee name
* @param sal an integer variable storing salary
* @param shift a String variable storing shift information
*/
public PartTimeEmployee(String id, String name, int sal, String shift)
{
// Invoke the super class constructor
super(id, name, sal);
this.shift=shift;
}
Java also allows casting the parent reference back to the child type.
Casting a parent object to child type is called downcasting because an object is being
casted to a class lower down in the inheritance hierarchy.
However, downcasting requires explicit type casting by specifying the child class name
in brackets.
For example,
PartTimeEmployee objPT1 = (PartTimeEmployee) objEmp;
// downcasting
The compiler does not generate error because the Employee class has a
displayDetails() method.
The difference here is between the compiler and the runtime behavior.
The compiler checks the accessibility of each method and field based on the class
definition whereas the behavior associated with an object is determined at runtime.
Since the object created was of PartTimeEmployee, the displayDetails()
method of PartTimeEmployee is invoked even though the object type is
Employee.
This is referred to as virtual method invocation and the method is referred to as
virtual method.
In other languages such as C++, the same can be achieved by using the keyword virtual.
© Aptech Ltd. Inheritance and Polymorphism/Session 10 36
Java provides the abstract keyword to create a super class that serves as a
generalized form that will be inherited by all of its subclasses.
The methods of the super class serve as a contract or a standard that the subclass
can implement in its own way.
Abstract method
The abstract method does not contain any ‘{}’ brackets and ends with a semicolon.
The syntax for declaring an abstract method is as follows:
Syntax
abstract <return-type> <method-name> (<parameter-list>);
where,
abstract: Indicates that the method is an abstract method.
For example,
public abstract void calculate();
© Aptech Ltd. Inheritance and Polymorphism/Session 10 37
Abstract class
Abstract class serves as a framework that provides certain behavior for other
classes.
The subclass provides the requirement-specific behavior of the existing framework.
Abstract classes cannot be instantiated and they must be subclassed to use the
class members.
The subclass provides implementations for the abstract methods in its parent class.
The syntax for declaring an abstract class is as follows:
Syntax
abstract class <class-name>
{
// declare fields
// define concrete methods
[abstract <return-type> <method-name>(<parameter-list>);]
}
© Aptech Ltd. Inheritance and Polymorphism/Session 10 38
where,
abstract: Indicates that the method is an abstract method.
For example,
public abstract Calculator
{
public float getPI(){ // Define a concrete method
return 3.14F;
}
abstract void Calculate(); // Declare an abstract method
}
Consider the class hierarchy as shown in following figure:
/**
* Abstract method
* @param val a float variable storing the value specified by user
*
* @return float
*/
abstract void calculate(float val);
}
/**
* Implement the abstract method to calculate area of circle
*
* @param rad a float variable storing value of radius
* @return void
*/
@Override
void calculate(float rad){
area = getPI() * rad * rad;
System.out.println(“Area of circle is:”+ area);
}
}
/**
* Implement the abstract method to calculate the perimeter
*
* @param width a float variable storing width
* @return void
*/
@Override
void calculate(float width){
perimeter = 2 * (length+width);
System.out.println(“Perimeter of the Rectangle is:”+ perimeter);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Shape objShape; // Declare the Shape object
String shape; // Variable to store the type of shape