JAVA OOPS AbstratClass&Interfaces
JAVA OOPS AbstratClass&Interfaces
• As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
• A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Test it NowOutput:
drawing rectangle 27
Difference between abstract class and interface
• Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be
instantiated.
• But there are many differences between abstract class and interface that are given
below.
• 3) Abstract class can have final, non-final, static and non-static variables.Interface
has only static and final variables.
• 6) An abstract class can extend another Java class and implement multiple
Java interfaces.An interface can extend another Java interface only.
• 8) A Java abstract class can have class members like private, protected,
etc.Members of a Java interface are public by default.
• 9)Example:
public abstract class Shape{
public abstract void draw();
}Example:
public interface Drawable{
void draw();
}Simply, abstract class achieves partial abstraction (0 to 100%) whereas
interface achieves fully abstraction (100%).
Example of abstract class and interface in Java
• Let's see a simple example where we are using interface and
abstract class both.
• //Creating interface that has 4 methods
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}