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());
}
}
}
The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.
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.
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.
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.
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 !!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With