Java Inheritance
Java Inheritance
Java Inheritance
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is
made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax
of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax
of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
class Calculation {
int z;
z = x + y;
z = x - y;
}
public class My_Calculation extends Calculation {
z = x * y;
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
Super Class/Parent Class: Superclass is the class from where a subclass inherits
you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in the previous
class.
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
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();
}}
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();
}}