Interface,Inheritance & 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:
- only public and abstract modifiers are allowed to use in interface. (Static are not allowed)
- 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(); } }
Leave a Reply to JitendraZaaCancel reply