Declaring a method when creating an object

∥☆過路亽.° 提交于 2019-11-29 16:01:12

问题


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?


回答1:


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();



回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/53960664/declaring-a-method-when-creating-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!