3. What Is Inheritance?
Inheritance in java is a
mechanism in which one
object acquires all the
properties and behaviors
of parent object.
4. Inheritance in Java can be best
understood in terms of Parent
and Child relationship, also
known as Super class(Parent)
and Sub class(child) in Java
language. Inheritance defines a
relationship between a Super
class and its Sub class. extends
and implements keywords are
used to describe inheritance in
Java
6. //Creating a SubClass
class A{
int a=10, b=20;
void showab(){
System.out.println(“a: “+a+ “b: ”+b);
}
}
//Creating a SubClass by extanding A class
class B extends A{
void sum(){
System.out.println(“Sum of a and b is: ”+(a+b));
}
}
//Creating Main Class
class Main{
public static void main(String args[]){
A obj1= new A();
obj1.showab();
B obj2= new B();
obj2.sum();
}
}
8. Inheritance
• As you can see, the subclass B
include all the members of its
super class, A.
• This is why class B can access
“a” and “b” and call showab().
• Also, include sum(), “a” and
“b” can be referred directly, as
if they were part of B class.
• Even though A is super class
for B, it is also a completely
independent, stand alone
class.
12. TYPES OF INHERITANCE
Based on number of ways inheriting the feature of
base class into derived class we have some types of
inheritance; they are:
• Single inheritance
• Multilevel inheritance
• Hierarchical inheritance
13. SINGLE INHERITANCE
When a class extends
another one class only then
we call it a single
inheritance.The below flow
diagram shows that class B
extends only one class
which is A. Here A is a
parent class of B and B
would be a child class of A
14.
15. MULTIPLE INHERITANCE
Here class C inherits class B
and class B inherits class A
which means B is a parent
class of C andA is a parent
class of B. So in this case class
C is implicitly inheriting the
properties and method of class
A along with B that’s what is
called multilevel inheritance.
16.
17. Hierarchical Inheritance
In this inheritance multiple classes inherits from a single class i.e
there is one super class and multiple sub classes. As we can see
from the below diagram when a same class is having more than
one sub class (or) more than one sub class has the same parent is
called as Hierarchical Inheritance.
22. SAMPLE PROGRAM
public class Animal{
}
public class Amphibians extends Animal{
}
public class Reptiles extends Animal{
}
public class Mammals extends Animal{
}
public class Birds extends Animal{
}
public class Main{
public static void main(String args[]){
// write your code
}
}
25. public class Animal{
eat();
reproduce();
sleep();
}
public class Amphibians extends Animal {
swim();
}
public class Reptiles extends Animal{
crawl();
}
public class Mammals extends Animal{
giveMilk();
}
public class Birds extends Animal {
fly();
}
public class Main{
public static void main (String args[] ){
Amphibians obj1=new Amphibians();
Reptiles obj2=new Reptiles();
Mammals obj3=new Mammals();
Birds obj4=new Birds();
}
}