Java 当我定义一个抽象类而不是声明时会发生什么。
在上面的代码中,包含方法定义的抽象方法。但在书中有这样一种说法:抽象方法应该只包含该方法的声明,而不是定义。当我执行这个程序时,它会在没有任何错误的情况下产生以下输出。请向我解释它是如何显示以下输出的Java 当我定义一个抽象类而不是声明时会发生什么。,java,abstract,Java,Abstract,在上面的代码中,包含方法定义的抽象方法。但在书中有这样一种说法:抽象方法应该只包含该方法的声明,而不是定义。当我执行这个程序时,它会在没有任何错误的情况下产生以下输出。请向我解释它是如何显示以下输出的 public class Temp { public static void main(String args[]) { A ref; B objB = new B(); C objC = new C(); ref = objB; ref.show();
public class Temp {
public static void main(String args[]) {
A ref;
B objB = new B();
C objC = new C();
ref = objB;
ref.show();
ref = objC;
ref.show();
}
}
abstract class A {
abstract void show();
{
System.out.println("In Class A");
}
}
class B extends A {
void show() {
System.out.println("In class B");
}
}
class C extends B {
void show() {
System.out.println("In Class C");
}
}
此Abstract方法在类A中没有实现:
In Class A
In Class A
In class B
In Class C
分号结束方法声明,但没有实现
下面的块是一个实例初始化块(在创建类的isntance时,在执行构造函数的代码之前执行),与抽象方法无关:
abstract void show();
如果您试图为抽象方法提供实现,它将如下所示,并且无法编译:
{
System.out.println("In Class A");
}
至于你得到的结果:
abstract void show()
{
System.out.println("In Class A");
}
您的抽象类不包含该方法的定义。抽象类包含一个抽象方法和一个初始值设定项块
In Class A // new B() causes the instance initialziation block of A to be executed before the (default) constructor of A
In Class A // new C() causes the instance initialziation block of A to be executed before the (default) constructor of A
In class B // first ref.show() executes B's show, since you assigned objB to ref
In Class C // second ref.show() executes C's show, since you assigned objC to ref
初始值设定项块在构造对象时运行-类似于构造函数(但可以有多个,并且不能有参数)。就像你写的一样:
abstract class A {
// Abstract method
abstract void show();
// Initializer block, completely unrelated to show
{
System.out.println("In Class A");
}
}
输出来自:
abstract class A {
// Abstract method
abstract void show();
// Constructor
public A()
{
System.out.println("In Class A");
}
}
先生,这证实了我的假设,非常有帮助@SSH什么输出行?先生,问题中显示的4行输出,每一行都属于哪一行代码的结果,而Eran先生在他的回答中提到了这一点,我要求确认我的假设和对您答案的理解,这对我来说是一个很好的学习
A ref;
B objB = new B(); // calls B's constructor, then A's constructor which prints "In Class A"
C objC = new C(); // calls C's constructor, then A's constructor which prints "In Class A"
ref = objB;
ref.show(); // prints "In Class B"
ref = objC;
ref.show(); // prints "In Class C"