Interface in Java
What is Interface in Java?
Interface in Java Language actually supports multiple inheritance, in contrast to C++. A class can only descend from one other class. Through implements, a class is able to implement numerous interfaces.
An interface may also have constants, static methods, nested interfaces, default methods, and abstract methods.
Interface in Brief
An Abstract Class called a Java Interface contains a method declaration but not its definition. An interface is implemented by a class in order to inherit abstract methods. An interface may additionally have constants, static methods, nested interfaces, default techniques, and abstract techniques.
It’s equivalent to writing a class to write an interface. However, a class describes an object’s characteristics and actions. Additionally, a class implements the behaviours found in an interface.
Syntax
interface Interface_Name{ public void method(); //Statements }
Implementing Java Interface
The class must implement interface methods since they lack a body before you can access them. All of an interface’s methods must be implemented by the class that implements it.
- We can ensure the security of implementation without worrying about the implementation component.
- Several inheritance is not permitted in Java, but you can use interfaces instead because you can create multiple interfaces.
Example
interface PrepInsta { public void method1(); public void method2(); } class Main implements PrepInsta { public void method1() { System.out.println("Here is method1 by Interface"); } public void method2() { System.out.println("Here is method2 by Interface"); } public static void main(String arg[]) { PrepInsta obj = new Main(); obj.method1(); obj.method2(); } }
Points to Remember:
- Interfaces cannot be used to construct objects, much like abstract classes.
- Interface methods lack a body; instead, the “implement” class supplies one.
- You must override every one of an interface’s methods when implementing it.
- By default, interface methods are public and abstract.
- The interface attributes are by default final, static, and public.
- A constructor cannot be included by an interface.
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment