Java p8
Java p8
showing method and variable access in both parent class and sub class.
Introduction
Inheritance in Java is a concept that acquires the properties from one class to other
classes; for example, the relationship between father and son. Inheritance in Java is a
process of acquiring all the behaviours of a parent object.
The concept of inheritance in Java is that new classes can be constructed on top of older
ones. You can use the parent class’s methods and properties when you inherit from an
existing class. You can also add additional fields and methods to your existing class.
The parent-child relationship, also known as the IS-A relationship, is represented by
inheritance.
One object can acquire all of a parent object’s properties and actions through the
technique of inheritance in Java Programming. It is a crucial component of OOPs (Object
Oriented programming system).
In Java, the idea of inheritance means that new classes can be built on top of existing
ones. When you derive from an existing class, you can use its methods and properties.
To your current class, you may also add new fields and methods.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
//Syntax for inheritance:-
Types of Inheritance:-
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
Note: Multiple inheritance is not supported in Java through class.
1. Single Inheritance :-
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
//Java program of single Inheritance
Class Animal{
int num=2;
Void eat(){
System.out.println(“eating…(Inside Super Class”);
}
}
Class Dog extends Animal{
Void bark(){
System.out.println(“barking…(Inside Child Class)”);
System.out.println(“Number of dog= “+num);
}
}
Class SingleInheritance{
Public static void main(String args[]){ //Main Method
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output
2. Multilevel Inheritance
3. Hierarchical Inheritance
When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
class Animal{
void eat(){
System.out.println(“eating…”);
}
}
class Dog extends Animal{
void bark(){
System.out.println(“barking…-Dog”);
}
}
class Cat extends Animal{
void meow(){
System.out.println(“meowing…-Cat”);
}
}
class Hierarchical_Inheritance{
public static void main(String args[]){ //Main Method
Cat obj=new Cat();
obj.meow();
obj.eat();
//obj.bark(); //Compile .Time.Error
Dog obj2 =new Dog();
obj2.bark();
obj2.eat();
}
}
Output: