You are on page 1of 23

Inheritance

Dr Sujit Das
Dept. of Computer Science and Engineering
NIT Warangal
What is Inheritance?
• Inheritance is an important pillar of OOP(Object Oriented Programming).
• It is the mechanism in java by which one class is allow to inherit the features
(fields and methods) of another class.
• Super Class: The class whose features are inherited is known as super class(or a
base class or a parent class).
• Sub Class: The class that inherits the other class is known as sub class(or a
derived class, extended class, or child class). The subclass can add its own fields
and methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we want
to create a new class and there is already a class that includes some of the code
that we want, we can derive our new class from the existing class. By doing this,
we are reusing the fields and methods of the existing class.
How to use inheritance in Java
class derived-class extends base-class
{
//methods and fields
}
Types of inheritance in java

Supported in Java Not Supported in Java


Single Inheritance Example
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[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
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();
}}
Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Why multiple inheritance is not supported in
java?
• To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
• Consider a scenario where A, B, and C are three classes. The C class inherits A and
B classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
• Since compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have same method or
different, there will be compile time error.
Multiple inheritance
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Super Keyword in Java
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.

class Animal{
String color="white";
}
class Dog extends Animal{ Output:
String color="black";
void printColor(){ black
System.out.println(color);//prints color of Dog class white
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
super can be used to invoke parent class
method
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
eating...
super.eat();
barking...
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
super is used to invoke parent class constructor
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
O/P:
super();
animal is created
System.out.println("dog is created"); dog is created
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
super example: real use
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
Output:
}
class Emp extends Person{
float salary; 1 ankit 45000
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}

}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
A simple example of inheritance
class SimpleInheritance {
// A simple example of inheritance.
// Create a superclass. public static void main(String args[]) {
class A { A superOb = new A();
int i, j;
void showij() { B subOb = new B();
System.out.println("i and j: " + i + " " + j); // The superclass may be used by itself.
}
} superOb.i = 10;
// Create a subclass by extending class A. superOb.j = 20;
class B extends A {
int k; System.out.println("Contents of superOb: ");
void showk() { superOb.showij();
System.out.println("k: " + k);
} System.out.println();
void sum() { /* The subclass has access to all public members of
System.out.println("i+j+k: " + (i+j+k));
} its superclass. */
} subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
output System.out.println("Contents of subOb: ");
Contents of superOb: subOb.showij();
i and j: 10 20 subOb.showk();
Contents of subOb: System.out.println();
i and j: 7 8 System.out.println("Sum of i, j and k in subOb:");
k: 9 subOb.sum();
Sum of i, j and k in subOb: }
}
i+j+k: 24
Member Access and Inheritance
// Create a superclass.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A {
int total;
void sum() {
total = i + j; // ERROR, j is not accessible here
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
// This program uses inheritance to extend Box.
class Box { // Here, Box is extended to include weight.
double width; class BoxWeight extends Box {
double height; double weight; // weight of box
double depth; // constructor for BoxWeight
// construct clone of an object BoxWeight(double w, double h, double d, double m)
Box(Box ob) { // pass object to constructor {
width = ob.width; width = w;
height = ob.height; height = h;
depth = ob.depth; depth = d;
} weight = m;
// constructor used when all dimensions specified }
Box(double w, double h, double d) { }
width = w;
height = h;
depth = d;
} class DemoBoxWeight {
// constructor used when no dimensions specified public static void main(String args[]) {
Box() { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
width = -1; // use -1 to indicate BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
height = -1; // an uninitialized double vol;
depth = -1; // box vol = mybox1.volume();
} System.out.println("Volume of mybox1 is " + vol);
// constructor used when cube is created System.out.println("Weight of mybox1 is " +
Box(double len) { mybox1.weight);
width = height = depth = len; System.out.println();
} vol = mybox2.volume();
// compute and return volume System.out.println("Volume of mybox2 is " + vol);
double volume() { System.out.println("Weight of mybox2 is " +
return width * height * depth; mybox2.weight);
} }
} }
When Constructors Are Called
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() { The output from this program is shown here:
System.out.println("Inside B's constructor.");
} Inside A’s constructor
} Inside B’s constructor
// Create another subclass by extending B.
class C extends B { Inside C’s constructor
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
Final Keyword In Java
• The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
• variable
• method
• class
• If you make any variable as final, you cannot change the value of final
variable(It will be constant).
Example of final variable
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output:Compile Time Error


Java final method
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
Java final class
If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
• Output:Compile Time Error
More about final
• Is final method inherited?
• Yes, final method is inherited but you cannot override it
• What is blank or uninitialized final variable?
• If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed,
• It can be initialized only in constructor.
• What is final parameter?
• If you declare any parameter as final, you cannot change the value of it.
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}

You might also like