Interface in Java?
An interface is a mechanism it is used to achieve abstraction.
An interface is a group of related methods with empty bodies.
Interfaces are similar to classes. It can have only abstract methods and static fields but default and static methods are added in Java 8 and private methods are added in Java 9. To implement an interface you must override all of its methods.
Points To Remember:
Interface methods are by default abstract and public.
An Interface attributes are by default public, static and final.
It supports multiple inheritances.
It supports to achieve abstraction.
It supports to achieve loose coupling.
It can extend one or more other interface.
It can be nested inside another interface.
Types of interfaces in Java?
1. Functional Interface
2. Marker interface
Functional Interfaces:
Functional interface have only one abstract method and can be used as lambda expressions or method references.
For example Runnable and Comparator.
Marker Interfaces:
Marker interface don’t declare any method. They are used to mark classes that implement them for special purpose by Java runtime or other tools.
For examples Serializable and Cloneable.
Syntax:
interface InterfaceName {
// Constant fields (public static final by default)
int CONSTANT = 100;
// Abstract method (public abstract by default)
void methodName();
// Default method
default void defaultMethod() {
System.out.println("Default implementation");
}
// Static method
static void staticMethod() {
System.out.println("Static method in interface");
}
// Private method
private void privateMethod() {
System.out.println("Private helper method");
}
}
import java.io.*;
// Interface Declared
interface testInterface {
// public, static and final
final int a = 100;
// public and abstract
void display();
}
// Class implementing interface
class TestClass implements testInterface {
// Implementing the capabilities of Interface
public void display(){
System.out.println("Suresh");
}
}
class Demo
{
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
Output:
Suresh
100
#Tags: | Java | Java Keywords | Java Methods | Java Questions | Java FAQs | Java questions and answers |
*Disclaimer: We have published the above images and information for reference purpose only, for any changes on the content we refer to visit the Official Website to get the latest info.
NOTE: Free Career Hub Employees will not call any candidates towards Job Offer or Job assistance. We never charge any candidates for Jobs. Please be aware of fraudulent Calls or Emails.