Inheritance Part-1
Inheritance Part-1
JAVA
Contents
2
class Fruit
{
//methods and fields
}
class Mango extends Fruit
{
//methods and fields
}
Single Inheritance (Example)
15
//Base-class
class Fruit
{
void fruitname() //Main Program
{
System.out.println("I am a Fruit"); public class SinglelevelInheritance
} {
} public static void main(String args[])
{
//Derived-class Mango obj = new Mango();
class Mango extends Fruit obj.fruitname();
{ obj.taste();
void taste() }
{ }
System.out.println("My taste is sweet");
}
}
Multilevel Inheritance (Concept)
16
class X
{
//methods and fields
}
class Y extends X
{
//methods and fields
}
class Z extends Y
{
//methods and fields
}
Multilevel Inheritance (Example)
18
Class X
{
public void methodX()
{ //Main Program
System.out.println("Class X method"); public static void main(String args[])
}
{
}
Class Y extends X Z obj = new Z();
{ //calling grand parent class method
public void methodY() obj.methodX();
{ //calling parent class method
System.out.println("class Y method"); obj.methodY();
}
}
//calling local method
Class Z extends Y obj.methodZ();
{ }
public void methodZ()
{
System.out.println("class Z method");
}
Hierarchical Inheritance (Concept)
19
Class Y Class Z
Hierarchical Inheritance (Syntax)
20
class X
{
//methods and fields
}
class Y extends X
{
//methods and fields
}
class Z extends X
{
//methods and fields
}
Hierarchical Inheritance (Example)
21
Multiple Inheritance:
When one class extends more than one classes then this is called multiple
inheritance. For example: Class C extends class A and B then this type of inheritance
is known as multiple inheritance.
Java doesn’t allow multiple inheritance. We will discuss later why java doesn’t allow
multiple inheritance and how we can use interfaces instead of classes to achieve the
same purpose.
Hybrid Inheritance:
Do yourself?
If you feel any problem ask the questions regarding this concept during the online
discussion session. (MS Team)
References
23
THANK YOU