Lab 9
Lab 9
Lab Objectives:
• Understanding the concept of polymorphism
• Understand the super keyword in inheritance
Software Required:
Netbeans IDE
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields. Perform following steps
• Create a class and its sub class both having same data member.
• Use super in child class to print the value of parent class variable.
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden. Perform following steps
• Create subclass of animal class with method bark() which prints "barking" and method eat()
same name as super class but it prints "eating meat"
• Write a print() method in subclass which call all the super and sub class methods.
Program: class
Animal
{
String eat;
void eat()
{
System.out.println("Eating");
}}
class Dog extends
Animal{ String Bark;
void printbark()
{
System.out.println("Barking");
}
String eat;
void printeat()
{
System.out.println("Eating meat");
}
}
}
Output:
Eating
Barking
Eating meat
The super keyword can also be used to invoke the parent class constructor. Create a scenario
in which above use of the super keyword is depicted.
Scenario:
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and
Sample Code:
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void
main(String args[]){ Bike2
obj = new Bike2(); obj.run();
}
class Test2{
public static void main(String args[]){
SBI obj1=new SBI();
ICICI obj2=new ICICI();
AXIS obj3=new AXIS();
System.out.println("SBI Rate of Interest: "+obj1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+obj2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+obj3.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8.0
ICICI Rate of Interest: 7.0
AXIS Rate of Interest: 9.0