0% found this document useful (0 votes)
54 views42 pages

Inheritance 2

The document discusses inheritance and method overriding in Java. It provides examples of single inheritance with a Person and Student class, multilevel inheritance with Animal, Dog and BabyDog classes, and abstract classes with a Shape class hierarchy. It also covers calling constructors, preventing overriding and inheritance using the final keyword, and hierarchical inheritance.

Uploaded by

Tuneer Saha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views42 pages

Inheritance 2

The document discusses inheritance and method overriding in Java. It provides examples of single inheritance with a Person and Student class, multilevel inheritance with Animal, Dog and BabyDog classes, and abstract classes with a Shape class hierarchy. It also covers calling constructors, preventing overriding and inheritance using the final keyword, and hierarchical inheritance.

Uploaded by

Tuneer Saha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Inheritance

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();

b=d; //superclass reference is holding subclass object


b.dispB();
//b.dispD(); error!!
}
Calling Constructors in inheritance
• Constructors are called in order of derivation, from super class to sub
class. Further, since super( ) must be the first statement executed in a
subclass’ constructor, this order is the same whether or not super( ) is
used. If super( ) is not used, then the default constructor of each
super class s will be executed. The following program illustrates when
constructors are executed:
class
{ A //Execution of constructors in inheritance
A()
{
System.out.println("A's constructor.");

}
}

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 create the equivalent of a named constant: A variable can be declared as


final. Doing so prevents its contents from being modified. This means that
you must initialize a final variable when it is declared. For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3; final
int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
To prevent method overriding: Sometimes, we do not want a superclass method to be overridden
in the subclass. Instead, the same superclass method definition has to be used by every subclass. In
such situation, we can prefix a method with the keyword final as shown below –
class A
{
final void meth()
{
System.out.println("This is a final method“);
}
}
class B extends A
{
void meth()
{
System.out.println("Illegal!");
}
}

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 class: is a restricted class that cannot be used to create


objects (to access it, it must be inherited from another class).

• Abstract method: can only be used in an abstract class, and it does


not have a body. The body is provided by the subclass (inherited
from).
• An abstract class can have both abstract and regular methods:
Abstract classes
drawing circle

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 %

int getRateOfInterest(){return 7;}


}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
//Bank b=new Bank(); error
b=new SBI();
b.meth();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
variables have a type
Each variable has a type, it may be primitive and non-primitive.
int data=30;
Here data variable is a type of int.
2) References have a type
class Dog{
public static void main(String args[]){
Dog d1;//Here d1 is a type of Dog
}
}
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of its superclass.
class Animal{}

class Dog extends Animal{


public static void main(String args[]){
Dog d1=new Dog();
}
}
• Static Binding and Dynamic Binding
• Connecting a method call to the method body is known as binding.
• There are two types of binding
• Static Binding (also known as Early Binding).
• Dynamic Binding (also known as Late Binding).
Dynamic binding
https://www.javatpoint.com/static-binding-and-dynamic-binding

Method overriding

NOTE: Refer class notes for other programs

You might also like