Interface, Inheritance and abstract class

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags , with 14 Comments on Interface, Inheritance and abstract class

What is abstract class, interface and inheritance in java. Source code and example

Interface,Inheritance & Abstract Class:-

Inheritance, Interface and abstract class

Inheritance :

The concept of extending a class by another class is known as inheritance.

A class which is inherited is known as Parent class, Base class or Super class.

A class which extends base class is known as Derived class or child class.


Abstract Class:

If a class contains one or more than one abstract method (abstract method is defined by keyword abstract and contains only declaration of that method.) then the class is declared with keyword abstract and known as abstract class.


Interface :

An Interface in java is known as Contract which must be followed by its implementing class (Child class).

If a class contains all methods as abstract method then, the class can be declared as Interface.

Important notes on interface:

  1. only public and abstract modifiers are allowed to use in interface. (Static are not allowed)
  2. If variable is defined inside the interface, then it must be initialized and it is final by default.

To read more on interface, refer this article.


Example 1:

interface IMario
{
  Void behavior();
}

class  Mario implements IMario
{
 public void behavior()
 {
     System.out.println("This is simple Mario");
 }
}

class  SuperMario implements IMario
{
  public void behavior()
  {
     System.out.println("This is Super Mario with power");
  }
}

class  TestMario
{
   public static void main(String args[])
   {
        System.out.println("----game started----");
        Imario obj=new Mario();
        Obj.behavior();
        System.out.println(-----After Mashroom-----");
        obj=new SuperMario();
        Obj.behavior();
        System.out.println(-----After Power Loss-----");
        obj=new Mario();
        Obj.behavior();
   }
}

o/p:-

—–Game Started——

This is simple Mario.

—–After Mashroom——

This is Super Mario with power.

—–After Power Loss—–

This is simple Mario.

Example 2:


interface A
{
   void displayA()
}

abstract class B
{
   public void displayB()
   {
     System.out.println("Display-B");
   }
   abstract public void display();
}

class  c extends B implements A
{
   Public void displayB()
  {
      System.out.println("Abstract Display-B");
  }

  public void displayA()
 {
     System.out.println("Display-A");
  }
}

class  TestClass
{
  public static void main(String args[])
 {
   C obj=new C();
   Obj.display();
   Obj.displayA();
   Obj.displayB();
 }
}