简体   繁体   English

具有匿名类型构造函数的对象类

[英]Object class with anonymous type constructor

I am creating an Object as a class variable with anonymous type. 我正在创建一个对象作为具有匿名类型的类变量。 There are no compilation errors. 没有编译错误。 My question is how to use the class? 我的问题是如何使用该类? How to call the methods that I am defining? 如何调用我正在定义的方法? Where is it used actually? 实际在哪里使用?

public class MyClass {

    Object o = new Object(){
        public void myMethod(){
            System.out.println("In my method");
        }
    };

}

I am not able to call the myMethod() of object o. 我无法调用对象o的myMethod() How to do that and when do we use this? 怎么做以及何时使用?

The only way to call a method of an anonymous class that is not part of the super class methods is to call it straight away: 调用不属于父类方法的匿名类的方法的唯一方法是立即对其进行调用:

new Object(){
    public void myMethod(){
        System.out.println("In my method");
    }
}.myMethod();

If you just store the anonymous class in an Object variable you won't be able to call its method any more (as you have figured out). 如果仅将匿名类存储在Object变量中,则将无法再调用其方法(如您所知)。

However the usefulness of such a construct seems quite limited... 但是,这种构造的用处似乎非常有限。

To do something like this, you should be having a method in Object class. 为此,您应该在Object类中有一个方法。 This in short means you need to override the method defined in Object class. 简而言之,这意味着您需要重写Object类中定义的方法。

Try something like: 尝试类似:

Object o = new Object(){
    public boolean equals(Object object){
        System.out.println("In my method");
        return this == object;//just bad example.
    }
};
Object o2 = new Object();
System.out.println(o.equals(o2));will also print "In my method"

Your variable type is Object , so the only methods that the compiler will let you call are the ones declared in Object . 您的变量类型为Object ,这样编译器将让你调用的唯一方法是在宣称的那些Object

Declare a non-anonymous class instead: 声明一个非匿名类:

private static class MyObject {
    public void myMethod() {
        System.out.println("In my method");
    }
};

MyObject o = new MyObject();

You can use interfaces: 您可以使用接口:

public interface MyInterface {
    public void myMethod();
}

In your MyClass 在您的MyClass中

public class MyClass {
    MyInterface o = new MyInterface() {
        @Override
        public void myMethod() {
            System.out.println("In my method");
        }
    };

    public void doSomething() {
        o.myMethod();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM