简体   繁体   English

Java类扩展的功能

[英]Functionality of an extension of a class in java

Assume the following classes exist: 假设存在以下类:

public class A {

  public void whatAreYou() {
    System.out.println("A");
  }
}

___________________________

public class B extends A {

  public void whatAreYou() {
    System.out.println("B");
  }
}

Now, we initialize a and b the following way: 现在,我们通过以下方式初始化a和b:

A b = new B();
b.whatAreYou();

_______________

B a = new A();
a.whatAreYou();

The question is: Do these programs work without any mistakes? 问题是:这些程序是否正常运行? If not, what can't of mistakes do they have? 如果没有,他们有什么错误呢?

My opinion: 我的意见:

I think the first program should work fine since the class B is an extension of the class A. But I can't tell what kind of object we have here. 我认为第一个程序应该运行良好,因为类B是类A的扩展。但是我无法确定我们在这里拥有哪种对象。 Does it possess every attribute of B too? 它也拥有B的所有属性吗? Besides that, it should print "B". 除此之外,它应该打印“ B”。

The second program does not work, but I lack a clear explanation. 第二个程序不起作用,但是我缺乏明确的解释。

Can somebody help me out? 有人可以帮我吗?

Placing your code in an IDE will surely help, as you can use a debugger to see what's happening step by step. 将代码放在IDE中肯定会有所帮助,因为您可以使用调试器逐步查看正在发生的情况。 You'll also be able to see the compile time error for 'B a = new A();' 您还将能够看到'B a = new A();'的编译时错误。 and go from there. 然后从那里去。 Regarding the functionality of the classes, in this case B is Overriding the 'whatAreYou()' method. 关于类的功能,在这种情况下,B是重写'whatAreYou()'方法。 This can be made clear with an @Override annotation. 可以使用@Override注释使之清楚。

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

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