Inheritance 2
Inheritance 2
Super class
Sub class
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[])
{
Animal A=new Animal();
Dog d=new Dog();
A.eat();
d.bark();
d.eat();
A.bark();//illegal
}}
Method Overriding
In a class hierarchy, when a method in a subclass has the same name
and type signature as a method in its superclass, then the method in
the subclass is said to override the method in the superclass. When
an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The
version of the method defined by the superclass will be hidden.
Method overriding: having same method
names+arguments in super and sub classes
class Person{ // Single level inheritance example
public String name;
public int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
}
}
public class Student extends Person {
public String branch;
public int Student_id;
public Student(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("Branch: "+branch);
System.out.println("Student ID: "+Student_id);
}
public static void main(String[] args) {
Student Stu= new Student("Krishna", 20, “ETC", 1256);
stu. displayStudent();
}
}
Output
Data of the Student class:
Name: Krishna
Age: 20
Branch: ETC
Student ID:1256
• How to Refer a subclass object
• There are two approaches to refer a subclass object. Both have
some advantages/disadvantages over the other. The
declaration affect is seen on methods that are visible at
compile-time.
1. First approach (Referencing using Superclass reference): A
reference variable of a superclass can be used to a refer any
subclass object derived from that superclass. If the methods are
present in SuperClass, but overridden by SubClass, it will be
the overridden method that will be executed.
2. Second approach (Referencing using subclass reference)
: A subclass reference can be used to refer its object.
public static void main(String[] args) {
Person person = new Student("Krishna", 20, "IT", 1256); // no issue
person. displayPerson(); //no issue
person.displayStudent(); //error: cannot find symbol
person.dispalyStudent();
}
Data of the Person class:
Name: Krishna
Age: 20
you can access the method of the superclass only i.e. display person().
Instead, if you try to access the subclass method i.e. display student() a
compile-time error is generated.
class Base
{
void dispB()
{
System.out.println("Super class " );
}
}
class Derived extends Base
{
void dispD()
{
System.out.println("Sub class ");
}
}
class Demo
{
public static void main(String args[])
{
Base b = new Base();
Derived d=new Derived();
}
}
class B extends A
{
B()
{
System.out.println("B's constructor.");
} }
class
{ C extends B
C()
{
System.out.println("C's constructor.");
} }
class CallingCons
{
public static void main(String args[])
{
c = new C();
}
}
A's constructor.
B's constructor.
C's constructor.
It executes all the super class constructors from A to C though the object
created is of class C.
final
The keyword final can be used in three situations in Java:
• To create the equivalent of a named constant.
• To prevent method overriding
• To prevent Inheritance
To prevent Inheritance: As we have discussed earlier, the subclass is treated as a specialized class
and superclass is most generalized class. During multi-level inheritance, the bottom most class will
be with all the features of real-time and hence it should not be inherited further. In such situations, we
can prevent a particular class from inheriting further, using the keyword final. For example –
final class A
{
// ...
}
class B extends A // ERROR! Can't subclass A
{
// ...
}
Multilevel inhertiance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}
Multilevel inheritance-example 2
class X
{
int i;
X(int i)
{
this.i=i;
System.out.println(“Created X”);
}
}
class Y extends X
{
int j;
Y(int i, int j)
{
super(i);
this.j = j;
System.out.println("Created Y" );
}
}
class Z extends Y
{
int k;
Z(int i, int j, int k)
{
super(i, j);
this.k = k;
System.out.println("Created Z" );
}
}
Class Main
{
PSVM(….)
{
class x1=new X(1);
class y1=new Y(10,20);
class z1=new Z(100,200,300);
}}
• OUTPUT
• ---------------
Created X
---------------
Created X
Created Y
---------------
Created X
Created Y
Created Z
---------------
• DESCRIPTION
• Here we have a created a hierarchy of classes, Z extending Y, which in turn extending from X. When we observe
the output we realize
• that when creating the sub-class object, the super-class constructor is called before the current constructor. So
when object of class Y I
• s created both Created X and Created Y are printed. Similarly when the object of class Z is created Created
X, Created Y and Created Z are printed
Hierarchial inheritance
When more than one classes inherit a same class then this is
called hierarchical inheritance. For example class B, C and D
extends a same class A. Lets see the diagram representation
of this:
Hierarchial inheritance-example
Abstract classes
• The abstract keyword is a non-access modifier, used for classes and
methods:
Abstract classes
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
Shape r=new Rectangle();//
r.draw();
} } Output: drawing circle
drawing rectangle
abstract class Bank{
abstract int getRateOfInterest();
void meth()
{ Output:
System.out.println(“Welcome”); Welcome
}} Rate of Interest is: 7 %
class SBI extends Bank{ Rate of Interest is: 8 %
Method overriding