Declaring a method when creating an object

3k Views Asked by At

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

There are 4 best solutions below

9
Andrew Tobilko On BEST ANSWER

java.lang.Object has no a methods declared (2), while the anonymous class returned by the class instance creation expression new Object() { public void a() {} } does (1).

Use Java 10's local variable type inference (var) to make the second option as valid as the first one.

var object = new Object() {
    public void a() {}
};
object.a();
0
Ivan On

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.

4
fastcodejava On

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

1
MAYANK On

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.