Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

java - 关于抽象类方法的快速提问(Quick Question in regards to the Methods in Abstract Classes)

I am a amateur programmer and I recently stumbled upon this special way of overriding a function when studying abstract classes: (我是一名业余程序员,最近我在研究抽象类时偶然发现了一种覆盖函数的特殊方法:)

abstract class Test {

    abstract String message();
}

public class Abstract {

    public static void main(String[] args) {

       String word = new Test() {

           String message() {
               return "Hello World";
           }

       }.message();

    }

}

I am confused at specific this part in the code: (我对代码中的这一部分感到困惑:)

String word = new Test() {

           String message() {
               return "Hello World";
           }

       }.message();

From looking at this specific section of the code, it seems that the abstract class is being "instantiated" (if I am using the term correctly). (从代码的这一特定部分来看,似乎抽象类正在“实例化”(如果我正确使用了该术语)。) However, I learned that abstract classes cannot be instantiated. (但是,我了解到不能实例化抽象类。)

I know this is quite of an obvious question, is it possible if you can explain to me what is happening when that part of the code is being complied? (我知道这是一个很明显的问题,是否可以向我解释在编译那部分代码时发生了什么?) I would be really grateful if you do so. (如果您这样做,我将不胜感激。)

Thank you, (谢谢,)

  ask by Simeon Tran translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From looking at this specific section of the code, it seems that the abstract class is being "instantiated" (通过查看代码的这一特定部分,似乎抽象类正在“实例化”)

Not really. (并不是的。) What you see is an instantiation of an anonymous class that extends the abstract Test class, and implements the abstract message() method of that class. (您将看到一个匿名类的实例,该类扩展了抽象Test类,并实现了该类的abstract message()方法。) The anonymous class is not abstract, and can therefore be instantiated. (匿名类不是抽象的,因此可以实例化。)

An equivalent code would be: (等效代码为:)

public class SubTest extends Test (
    String message() {
        return "Hello World";
    }
}

public class Abstract {

    public static void main(String[] args) {

        String word = new SubTest().message();

    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...