inheritance and interface in java code example

Example 1: Inheritance in java

// Multiple inheritance in java
interface M
{
   public void helloWorld();
}
interface N
{
   public void helloWorld();
}
// implementing interfaces
public class MultipleInheritanceExample implements M, N
{
   public void helloWorld()
   {
      System.out.println("helloWorld() method");
   }
   public static void main(String[] args) 
   {
      MultipleInheritanceExample obj = new MultipleInheritanceExample();
      obj.helloWorld();
   }
}

Example 2: Inheritance in java

// Hierarchical 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 3: Inheritance in java

// Hybrid 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();
   }
}

Tags:

Java Example