Cleanable interface in Java is also a marker interface that belong to java.lang package. It generates replica (copy) of an object with different name. We can implement the interface in the class of which class object to be cloned. It indicates the clone() method of the Object class. If we do not implement the Cloneable interface in the class and invokes the clone() method, it throws the ClassNotSupportedException.
Note that a class that implements the Cloneable interface must override the clone() method with a public method. Let's see an example.
Product.java
- import java.util.Scanner;
- public class Product implements Cloneable
- {
- int pid;
- String pname;
- double pcost;
- //Product class constructor
- public Product (int pid, String pname, double pcost)
- {
- this.pid = pid;
- this.pname = pname;
- this.pcost = pcost;
- }
- //method that prints the detail on the console
- public void showDetail()
- {
- System.out.println("Product ID: "+pid);
- System.out.println("Product Name: "+pname);
- System.out.println("Product Cost: "+pcost);
- }
- public static void main (String args[]) throws CloneNotSupportedException
- {
- //reading values of the product from the user
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter product ID: ");
- int pid = sc.nextInt();
- System.out.print("Enter product name: ");
- String pname = sc.next();
- System.out.print("Enter product Cost: ");
- double pcost = sc.nextDouble();
- System.out.println("-------Product Detail--------");
- Product p1 = new Product(pid, pname, pcost);
- //cloning the object of the Product class using the clone() method
- Product p2 = (Product) p1.clone();
- //invoking the method to print detail
- p2.showDetail();
- }
- }
Output:
Enter product ID: 139872
Enter product name: Printer
Enter product Cost: 3459.67
-------Product Detail--------
Product ID: 139872
Product Name: Printer
Product Cost: 3459.67