Pages

Abstraction in java (interface class)

interface in java :: futureX

Interface: An interface is a blueprint of a class. It has static constants and abstract methods.
The interface is a mechanism to achieve abstraction in java. There can be only abstract methods in the interface. It is used to achieve fully abstraction and multiple inheritance in Java.

Why use Interface?

It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling
the java compiler converts methods of interface as public and abstract, data members as public,final and static by default.

Example :

interface Shape{
void draw();
}

class Circle implements Shape{
public void draw(){System.out.println("drawing circle");}
}

class Rectangle implements Shape{
public void draw(){System.out.println("drawing rectangle");}
}

class Test{
public static void main(String args[]){
Shape S=new Circle();
S.draw();

}}

multiple inheritance by interface :

interface Shape{
void draw();
}

interface Color{
String getColor();
}


class Rectangle implements Shape,Color{
public void draw(){System.out.println("drawing rectangle");}
public String getColor(){return("red");}
}

class Test{
public static void main(String args[]){
Rectangle s=new Rectangle();
s.draw();
System.out.println(s.getColor());
}}

                                            JAVA TUTORIALS HOMEPAGE

No comments:

Post a Comment