Java 中的多态方法(来自背诵)
这是我大学 200 级计算机科学课程的未评分背诵作业。我只是寻求我自己的理解。
在下面的代码中,为什么第4行打印B和A而不是B和B?另外,在 Intellij 中,我被告知 A.show(D obj) 和 B.show(B obj) 中 A 之后的 obj 未使用,而 A.show(A obj) 和 A.show(B obj)被使用,尽管它们看起来都以相同的方式使用;只是为了确定要使用哪个重载方法。
public class Polymor {
class A {
public String show(D obj) {
return ("A and D");
}
public String show(A obj) {
return ("A and A");
}
}
class B extends A {
public String show(B obj) {
return ("B and B");
}
public String show(A obj) {
return ("B and A");
}
}
class C extends B {}
class D extends B {}
public static void main(String[] args) {
Polymor outerclass = new Polymor();
A a1 = outerclass.new A();
A a2 = outerclass.new B();
B b = outerclass.new B();
C c = outerclass.new C();
D d = outerclass.new D();
System.out.println("1:" + a1.show(b));
System.out.println("2:" + a1.show(c));
System.out.println("3:" + a1.show(d));
System.out.println("4:" + a2.show(b));
System.out.println("5:" + a2.show(c));
System.out.println("6:" + a2.show(d));
System.out.println("7:" + b.show(b));
System.out.println("8:" + b.show(c));
System.out.println("9:" + b.show(d));
}
}
除了我提到的输出之外,我理解所有输出。我在网上搜索了这个未使用的参数问题,但找不到任何内容。
This is for an ungraded recitation assignment for a 200 level CS course at my University. I am just asking for my own understanding.
In the following code, why does line 4 print B and A instead of B and B? Also, in Intellij I am told that the objs after the A in A.show(D obj) and B.show(B obj) are not used, while the A.show(A obj) and A.show(B obj) are used, even though they are seemingly both used the same way; just to identify which overloaded method to use.
public class Polymor {
class A {
public String show(D obj) {
return ("A and D");
}
public String show(A obj) {
return ("A and A");
}
}
class B extends A {
public String show(B obj) {
return ("B and B");
}
public String show(A obj) {
return ("B and A");
}
}
class C extends B {}
class D extends B {}
public static void main(String[] args) {
Polymor outerclass = new Polymor();
A a1 = outerclass.new A();
A a2 = outerclass.new B();
B b = outerclass.new B();
C c = outerclass.new C();
D d = outerclass.new D();
System.out.println("1:" + a1.show(b));
System.out.println("2:" + a1.show(c));
System.out.println("3:" + a1.show(d));
System.out.println("4:" + a2.show(b));
System.out.println("5:" + a2.show(c));
System.out.println("6:" + a2.show(d));
System.out.println("7:" + b.show(b));
System.out.println("8:" + b.show(c));
System.out.println("9:" + b.show(d));
}
}
I understand all of the outputs except for the ones I mentioned. I have searched online for this unused parameter issue but cannot find anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论