Declaring a method when creating an object

Viewed 2370

Why first way is correct, but second isn't?


First way:

new Object() {
    public void a() {
        /*code*/
    }
}.a();

Second way:

Object object = new Object() {
    public void a() {
        /*code*/
    }
};

object.a();

And where can I find more information about it?

4 Answers

In the second option, you assign your new object to a reference of type Object. Because of this, only methods defined in java.lang.Object could be called on that reference.

And in the first option, you basically create new object of anonymous class that extends java.lang.Object. That anonymous class has the additional method a(), which is why you can call it.

Java is statically typed. When you say object.a() it is looking for the method a in the Object class which is not present. Hence it does not compile.

What you can do is get the method of object using reflection as shown below :

Object object = new Object() {
  public void a() {
     System.out.println("In a");
  }
}

Method method = object.getClass().getDeclaredMethod("a");
method.invoke(object, null);

This would print

In a

Don't worry, you will have to do a bit of correction Both are ways to access the private member of a class. By using first way you don' have to pre-declare the method.ex: -

public class demo {

    public static void main(String[] args) {
    new Object() {
        public void a() {
            /*code*/
            System.out.println("Hello");
        }
    }.a();

}

}

But by using second way you will have to explicitly declare the method a(); either in abstract class or in interface then you can override it. like: -

interface Object
{
public void a();
}
class demo {

public static void main(String[] args) {
    Object object = new Object() {
        public void a() {
            System.out.println("Hello");
        }

    }; object.a();


}

}

I hope it will help a bit.

Related