Inheritance example in Java
Example 1: inheritance in java
class Animal
{
void eat()
{
System.out.println("Animal is eating.");
}
}
class Lion extends Animal
{
public static void main(String[] args)
{
Lion obj = new Lion();
obj.eat();
}
}
Example 2: Inheritance in java
class Animal
{
void eating()
{
System.out.println("animal eating");
}
}
class Lion extends Animal
{
void roar()
{
System.out.println("lion roaring");
}
}
public class Cub extends Lion
{
void born()
{
System.out.println("cub drinking milk");
}
public static void main(String[] args)
{
Animal obj1 = new Animal();
obj1.eating();
Lion obj2 = new Lion();
obj2.eating();
obj2.roar();
Cub obj3 = new Cub();
obj3.eating();
obj3.roar();
obj3.born();
}
}
Example 3: Inheritance in java
class Animal
{
void eating()
{
System.out.println("animal eating");
}
}
class Lion extends Animal
{
void roar()
{
System.out.println("lion roaring");
}
}
public class Dog extends Animal
{
void bark()
{
System.out.println("dog barking");
}
public static void main(String[] args)
{
Animal obj1 = new Animal();
obj1.eating();
Lion obj2 = new Lion();
obj2.eating();
obj2.roar();
Dog obj3 = new Dog();
obj3.eating();
obj3.bark();
}
}
Example 4: Inheritance in java
class A
{
public void display()
{
System.out.println("class A display method");
}
}
interface B
{
public void print();
}
interface C
{
public void print();
}
public class HybridInheritanceDemo extends A implements B, C
{
public void print()
{
System.out.println("implementing print method");
}
public void show()
{
System.out.println("show method of class HybridInheritanceDemo");
}
public static void main(String[] args)
{
HybridInheritanceDemo obj = new HybridInheritanceDemo();
obj.show();
obj.print();
}
}
Example 5: Inheritance in java
import java.util.*;
class Animal
{
void eat()
{
System.out.println("Animal is eating.");
}
}
class Lion extends Animal
{
void roar()
{
System.out.println("lion is roaring.");
}
public static void main(String[] args)
{
Lion obj = new Lion();
obj.eat();
obj.roar();
}
}
Example 6: Inheritance in Java
Java Inheritance (Subclass and Superclass)
In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:
subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.