Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we create object of interface in java? [duplicate]

Tags:

java

interface

How is this code working i m totally puzzled....

package com.servletpack.examples;

interface check {
    public void message();
}
public class Interface {
    public static void main(String[] args) {
        try {
            check t = new check() {//how????????????????
                public void message() {
                    System.out.println("Method defined in the interface");
                }
            };
            t.message();
        } catch (Exception ex) {
            System.out.println("" + ex.getMessage());
        }
    }
}
like image 749
swapyonubuntu Avatar asked Jun 02 '13 06:06

swapyonubuntu


People also ask

How do you duplicate an object in Java?

The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.

Can you create an object of an interface in Java?

Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass) Interface methods do not have a body - the body is provided by the "implement" class.

Which method is used to create a duplicate object?

The clone() method of Object class is used to clone an object. The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create.

Does clone create new object in Java?

Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.


2 Answers

It is anonymous class. Your check class is an interface. Anonymous class defines an implementation of given interface on the fly. So it saves you from creating a seperate class for Interface's implementation. This approach is only useful when you know you will never require this implementation any where else in the code.

Hope this explanation helps !!

like image 195
Abhay Agarwal Avatar answered Sep 19 '22 20:09

Abhay Agarwal


With that syntax, you create an anonymous class, which is perfectly legal.

Internally, anonymous classes are compiled to a class of their own, called EnclosingClass$n where the enclosing class' name precedes the $ sign. and n increases for each additional anonymous class. This means that the following class is being created:

class Interface$1 implements check {
     public void message() {
         System.out.println("Method defined in the interface");
     }
}

Then, the code in main compiles to internally use the newly-defined anonymous class:

check t = new Interface$1();
t.message();
like image 43
FThompson Avatar answered Sep 21 '22 20:09

FThompson