DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-69 Understanding Java Interfaces and the final Keyword

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:

  1. Interface is not a class.
  2. All methods in an interface are abstract by default. They do not have a method body.
  3. An interface is 100% abstract and cannot have constructors.
  4. The implements keyword is used to inherit an interface, instead of extends.
  5. Interface methods cannot have objects.
  6. 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();
    }
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
sudamsiths profile image
Sadira Sudamsith

Super

Collapse
 
tamilselvan1812 profile image
Tamilselvan K

Thankyou.