Inheritance and Its Types
Inheritance and Its Types
Inheritance and Its Types
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase the
functionality.
class Employee{
float salary=40000;
int bonus=10000;
Prepared By : Kanojiya Babloo Rajendra
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class
as well as of Employee class i.e. code reusability.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
class TestInheritance{
d.bark();
d.eat();
}}
Output:
barking...
eating...
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
Prepared By : Kanojiya Babloo Rajendra
void bark(){System.out.println("barking...");}
void weep(){System.out.println("weeping...");}
class TestInheritance2{
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void meow(){System.out.println("meowing...");}
class TestInheritance3{
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing... eating...
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.
class A{
void msg(){System.out.println("Hello");}
class B{
void msg(){System.out.println("Welcome");}
}
Prepared By : Kanojiya Babloo Rajendra
C obj=new C();
}
Compile Time Error