Interface in Java
In this tutorial we will learn about the concept of Interface in java. We learn about interface through a simple code.
What is Interface?
The interface. is a blueprint of classes. An interface is a method to achieve 100% abstraction and multiple inheritance. An interface can have methods and variables only. An interface can have only abstract methods, not the body of the method. An interface specifies what a class must do and not what to do. Since java does not support multiple inheritance we can achieve it through the interface.The interface represents the IS-A relationship.
Syntax:
- interface interface_name{
- // declare constant fields
- // declare methods that abstract
- // by default.
- }
Use of Interface
1. By using the interface we can achieve multiple inheritance.
2. Interface is used to achieve 100% abstraction.
3. It can also be used to achieve loose coupling.
Code
interface shape{
void draw();
}
class rectangle implements shape{
public void draw(){
System.out.println("Drawing Rectangle");
}
}
class square implements shape{
public void draw(){
System.out.println("Drawing Square");
}
}
class sample{
public static void main(String args []){
shape s=new square();
s.draw();
}
}
Output:
Drawing Square
Project Files
/
Loading...
| .. | ||
| This directory is empty. | ||