简体   繁体   English

对象创建期间的java覆盖

[英]java override during object creation

in the following java code a JButton is created but at the same time one of its methods gets overridden. 在下面的java代码中创建了一个JButton,但同时它的一个方法被覆盖。 Qestion: is there a name for overriding in this way while creating the object? 问题:创建对象时是否有以这种方式覆盖的名称?

the code: 代码:

   JButton myButton;
   myButton = new JButton ("ok"){

        @Override
        public void setText(String text) {
            super.setText(text +", delete");
        }

the jbutton's label is now "ok, delete" jbutton的标签现在是“ok,delete”

That's an anonymous class. 这是一个匿名课程。 From Java in a Nutshell 来自Java的坚果壳

An anonymous class is a local class without a name. 匿名类是没有名称的本地类。 An anonymous class is defined and instantiated in a single succinct expression using the new operator. 使用new运算符在单个简洁表达式中定义和实例化匿名类。 While a local class definition is a statement in a block of Java code, an anonymous class definition is an expression, which means that it can be included as part of a larger expression, such as a method call. 虽然本地类定义是Java代码块中的语句,但匿名类定义是表达式,这意味着它可以作为更大表达式的一部分包含在内,例如方法调用。 When a local class is used only once, consider using anonymous class syntax, which places the definition and use of the class in exactly the same place. 当本地类只使用一次时,请考虑使用匿名类语法,它将类的定义和使用放在完全相同的位置。

It's a common means of providing a specialisation of a base class without explicitly defining a new class via the class expression. 这是提供基类特化而不通过class表达式显式定义新类的常用方法。

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

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