Can we write an interface without any methods in java?

Java 8Object Oriented ProgrammingProgramming

Yes, you can write an interface without any methods. These are known as marking interfaces or, tagging interfaces.

A marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented.

Example

Consider the following example, here we have class with name Student which implements the marking interface Cloneable. In the main method we are trying to create an object of the Student class and clone it using the clone() method.

 Live Demo

import java.util.Scanner;
public class Student implements Cloneable {
   int age;
   String name;
   public Student (String name, int age){
      this.age = age;
      this.name = name;
   }
   public void display() {
      System.out.println("Name of the student is: "+name);
      System.out.println("Age of the student is: "+age);
   }
   public static void main (String args[]) throws CloneNotSupportedException {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your age: ");
      int age = sc.nextInt();
      Student obj = new Student(name, age);
      Student obj2 = (Student) obj.clone();
      obj2.display();
   }
}

Output

Enter your name:
Krishna
Enter your age:
29
Name of the student is: Krishna
Age of the student is: 29

In this case the cloneable interface does not have any members, you need to implement this just to mark or tag the class indicating that its objects are cloneable. If we do not implement this interface you cannot use the clone method of the Object class.

If you Still try, it throws a java.lang.CloneNotSupportedException exception.

Example

In the following Java program, we are trying to use the clone() method of the Object class without implementing the Cloneable interface.

 Live Demo

import java.util.Scanner;
public class Student{
   int age;
   String name;
   public Student (String name, int age){
      this.age = age;
      this.name = name;
   }
   public void display() {
      System.out.println("Name of the student is: "+name);
      System.out.println("Age of the student is: "+age);
   }
   public static void main (String args[]) throws CloneNotSupportedException {
      Student obj = new Student("Krishna", 29);
      Student obj2 = (Student) obj.clone();
      obj2.display();
   }
}

Run time Exception

This program gets compiled successfully but, while executing it raises a runtime exception as −

Output

Exception in thread "main" java.lang.CloneNotSupportedException: Student
   at java.base/java.lang.Object.clone(Native Method)
   at Student.main(Student.java:15)
raja
Published on 04-Jul-2019 17:47:03
Advertisements