当您动态创建实例时,在 Java 中它被称为什么?
在代码中,
class MyObject {
public String doThing() {
return "doh";
}
}
class MyClass {
private myObject = null;
public MyClass() {
myObject = new MyObject() {
public String doThing() {
return "huh?";
}
};
}
当 myObject 被分配一个新对象时,它被称为什么?从技术上讲,我试图找出“doThing”是否覆盖了 MyObject 中的方法,或者它是否重新定义了它,但我不知道要搜索什么来找到答案 - 并且不知道在不知道它是什么的情况下要问什么问题当您动态创建对象的新实例并为其提供实现时调用。
In code,
class MyObject {
public String doThing() {
return "doh";
}
}
class MyClass {
private myObject = null;
public MyClass() {
myObject = new MyObject() {
public String doThing() {
return "huh?";
}
};
}
What is it called when myObject is assigned a new object? I'm technically trying to find out if the 'doThing' overrides the method from MyObject, or if it redefines it, but I have no idea what to search on to find an answer - and no idea what question to ask without knowing what it's called when you create a new instance of an object on the fly and give it an implementation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您正在创建一个匿名内部类,它是
MyObject
的子类,所以是的,您正在重写doThing
方法,如果这是您想要的问。顺便说一句,匿名类就像命名类一样,它们在
.class
文件中有自己的字节码,其命名就像它们的封闭类一样,带有美元符号和数字后缀。如果你想自己实验,可以使用
myObject
的方法getClass()
并提取有关它的信息,如名称、父级、实现的接口、泛型参数, ETC。You are creating an anonymous inner class that is a subclass of
MyObject
, so yes, you are overriding thedoThing
method, if is that what you ask.By the way, anonymous classes are like named classes, they have their own bytecode in their
.class
file, that is named like their enclosing class suffixed with a dollar sign and an number.If you want to experiment by yourself, you can use the method
getClass()
ofmyObject
and extract information about it, like the name, parent, implemented interfaces, generic arguments, etc.这就是所谓的匿名内部类。
鉴于
doThing()
方法与其超类中的公共方法具有相同的签名,因此它会覆盖它。最好的确定方法是在子类中的方法上添加@Override注解:如果带有此注解的方法没有重写任何方法,编译器将生成编译错误。
That's called an anonymous inner class.
Given that the
doThing()
method has the same signature as a public method in its superclass, it overrides it.The best way to be sure is to add the @Override annotation to the method in the subclass: the compiler will generate a compilation error if the method with this annotation doesn't override any method.
这个结构的名称是匿名内部类
你会发现很多关于这些的文档谷歌
The name for this structure is Anonymous inner class
You'll find plenty of docs about these with Google
在Java 中,所有非最终实例方法都可以重写(即虚拟方法)。这同样适用于内部类,因此您的代码会覆盖
MyObject
的doThing()
方法。In Java all non-final instance methods are subject to override (i.e. virtual). This equally applies to inner classes, so your code overrides
MyObject
'sdoThing()
method.是的,
doThing()
方法被重写。这相当于一个匿名类继承 MyObject 的行为,然后重写它。Yes, the
doThing()
method is overridden. This is equivalent to an anonymous class that is inheriting the behavior of MyObject and then overriding it.