Java - inline class definition

前提是你 提交于 2019-11-27 18:03:22

问题


I've seen a couple of examples similar to this in Java, and am hoping someone can explain what is happening. It seems like a new class can be defined inline, which seems really weird to me. The first printout line is expected, since it is simply the toString. However the 2nd seems like the function can be overriden inline. Is there a technical term for this? Or any documentation which goes into more depth? Thanks!

If I have the following code:

public class Apple {
    public String toString() {
        return "original apple";
    }
}

public class Driver {
    public static void main(String[] args) {
        System.out.println("first: " + new Apple());
        System.out.println("second: " + 
            new Apple() {
                public String toString() {
                    return "modified apple";
                }
            }
        );
    }
}

The code outputs:

first: original apple
second: modified apple

回答1:


It is an anonymous inner class. You can find some more information about it at the Java documentation link for Inner Classes. EDIT I am adding a better link describing anonymous inner classes, as the Java documentation leaves something to be desired. /EDIT

Most people will use Anonymous inner classes to define listeners on the fly. Consider this scenario:

I have a Button, and when I click it I want it to display something to the console. But I do not want to have to create a new class in a different file, and I don't want to have to define an inner class later in this file, I want the logic to be immediately available right here.

class Example {
    Button button = new SomeButton();

    public void example() {
        button.setOnClickListener(new OnClickListener() {
            public void onClick(SomeClickEvent clickEvent) {
                System.out.println("A click happened at " + clickEvent.getClickTime());
            }
        });
    }

    interface OnClickListener {
        void onClick(SomeClickEvent clickEvent);
    }

    interface Button {
        void setOnClickListener(OnClickListener ocl);
    }
}

The example is somewhat contrived and obviously not complete, but I think it gets the idea across.




回答2:


What is happening in your code is that you are implicitly subclassing Apple with an anonymous inner class and overriding its toString() method.




回答3:


It's called an annonymous inner class, you can read about it here and here.



来源:https://stackoverflow.com/questions/8913406/java-inline-class-definition

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