Pract 6
Pract 6
An interface in Java is a blueprint of a class. It has sta c constants and abstract methods.
The interface in Java is a mechanism to achieve abstrac on. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstrac on and mul ple inheritance in
Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
There are mainly three reasons to use interface. They are given below.
AD
Syntax:
1. interface <interface_name>{
2.
5. // by default.
6. }
Example:
1. interface Animal {
2. void eat();
3. void sleep();
4. }
In this example, the Animal interface declares two method signatures: eat() and sleep(). Any class
implemen ng the Animal interface must provide concrete implementa ons for these methods.
AD
Since Java 8, interface can have default and sta c methods which is discussed later.
The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds
public, sta c and final keywords before data members.
In other words, Interface fields are public, sta c and final by default, and the methods are public and
abstract.
In this example, the Printable interface has only one method, and its implementa on is provided in
the A6 class.
1. interface printable{
2. void print();
3. }
8. obj.print();
9. }
10. }
Output:
Hello
AD
File: TestInterface1.java
2. interface Drawable{
3. void draw();
4. }
8. }
11. }
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
16. d.draw();
17. }}
Test it Now
Output: