Full Stack Web Development Internship Program
- 5k Enrolled Learners
- Weekend/Weekday
- Live Class
The Interface is an Important aspect of OOPs in Java. In this article, we will understand what is implements in Java and how it is used in the following manner:
“Implements” is a keyword which is used to implement an interface in the java language. So, What is an interface in Java?
An Interface is like a Java Class that only has static constants and abstract methods. A java class can implement these interfaces by using the keyword implements. Multiple interfaces can be implemented at a time. All methods are abstract and public.
Two main rules when it comes to interfaces
It must be abstract with abstract methods.
Any number of interfaces can be implemented by the class.
Multiple inheritances are not supported by java but this can be achieved by using interfaces. More than one Interface can be implemented.
Syntax:
class classname implements interfacename
class Dog implements Pet
interface Animal { public void eat(); public void travel(); } public class PetInt implements Animal { public void eat() { System.out.println("Pet eats"); } public void travel() { System.out.println("Pet travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { PetInt m = new PetInt(); m.eat(); m.travel(); } }
OUTPUT:
In the above code, an interface is created and is implemented using the implements keyword.
interface Animal { public void eat(); public void travel(); }
An interface is created with two methods declared. The class PetInt implements this interface.
public void eat() { System.out.println("Pet eats"); } public void travel() { System.out.println("Pet travels"); }
Two methods are created called eat and travel respectively. Both methods have simple print statements.
In the main function, we create a pet variable m and call both the methods for it. This is how the interface is implemented.
Implements keyword is used when we want to inherit an interface, whereas the extends keyword is used for inheriting classes.
Multiple interfaces can be inherited at a time whereas only one class is inherited at a time.
A subclass can override some methods of the superclass whereas all methods are implemented from interfaces by class.
For a more In-depth difference, you can refer to our other Blog.
With this, we come to an end of this Implements in Java article. I hope you got an understanding of what exactly Implements are and how are they used.
Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.
edureka.co