What is an Interface?
An interface in Java is not a class. It is a blueprint for a class, and it defines a set of abstract methods that any implementing class must override.
Rules of Interfaces in Java:
- Interface is not a class.
- All methods in an interface are abstract by default. They do not have a method body.
- An interface is 100% abstract and cannot have constructors.
- The implements keyword is used to inherit an interface, instead of extends.
- Interface methods cannot have objects.
- We must override all of its methods in another class.
Example Code:
public interface OfficeRules { // Interface is not a class
public void comeOnTime(); // Interface methods do not have a body
public void getSalary(); // Interface methods are by default abstract
public void takeLeave(); // An interface cannot contain a constructor
}
public class Employee1 implements OfficeRules { // Use "implements" to implement an interface
public void comeOnTime() {
System.out.println("10am"); // Must override all methods of the interface
}
public void getSalary() {
// Implementation can be added here
}
public void takeLeave() {
// Implementation can be added here
}
public static void main(String[] args) {
Employee1 em = new Employee1();
em.comeOnTime();
}
}
The final Keyword in Java
The final keyword in Java is used to restrict modification. It can be applied to:
- Classes
- Methods
- Variables
- Parameters
Behavior of final:
- A final class cannot be inherited.
- A final method cannot be overridden in a subclass.
- A final variable’s value cannot be changed.
- A final parameter value cannot be modified inside the method.
Top comments (2)
Super
Thankyou.