gpt4 book ai didi

Java - 重载和覆盖

转载 作者:行者123 更新时间:2023-11-30 05:00:53 25 4
gpt4 key购买 nike

01    class SubClass extends SuperClass {}
02 class AppSuperClass {
03 /**
04 * @param superClass
05 */
06 public void print(SuperClass superClass) {
07 System.out.println("AppSuperClass:superclass is parameter");
08
09 }
10 /**
11 * @param subClass
12 */
13 public void print(SubClass subClass) {
14 System.out.println("AppSuperClass:subclass is parameter");
15
16 }
17 }
18
19 class AppSubClass extends AppSuperClass {
20 /**
21 * @param superClass
22 */
23 public void print(SuperClass superClass) {
24 System.out.println("AppSubClass:superclass is parameter");
25
26 }
27 /**
28 * @param subClass
29 */
30 public void print(SubClass subClass) {
31 System.out.println("AppSubClass:subclass is parameter");
32
33 }
34 }
35 public class OverloadedTest {
36 public static void main(String[] args) {
37 AppSuperClass appSuperClass = new AppSuperClass();
38 AppSuperClass appSubClass = new AppSubClass();
39 SuperClass superClass = new SuperClass();
40 SuperClass subClassInstance = new SubClass();
41 /*
42 * Making request to print AppSuperClass
43 * 1. Passing SuperClass instance
44 * 2. Passing SubClass instance (*make note of the type) <img src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1304052800g" alt=":)" class="wp-smiley">
45 */
46
47 appSuperClass.print(superClass);
48 appSuperClass.print(subClassInstance);
49 /*
50 * Above is repeated with AppSubClass instance
51 */
52 appSubClass.print(superClass);
53 appSubClass.print(subClassInstance);
54 }
55
56 }

当我运行这个时,我得到

       AppSuperClass:superclass is parameter
AppSuperClass:superclass is parameter
AppSubClass:superclass is parameter
AppSubClass:superclass is parameter

如何获得

           AppSuperClass:superclass is parameter
AppSuperClass:subclass is parameter
AppSubClass:superclass is parameter
AppSubClass:subclass is parameter

作为o/p而不改变任何对象的类型?

最佳答案

你的问题不是很清楚,但听起来你基本上是在执行时重载之后,这在Java中根本不存在。重载在编译时完全解决。一种选择是:

public void print(SuperClass superClass) {
if (superClass instanceof SubClass) {]
print((SubClass) superClass);
return;
}
System.out.println("AppSuperClass:superclass is parameter");
}

请注意,您还需要在重写中执行此操作,或者有一个执行此操作的模板方法,以及一个可以在子类中重写的单独的 printImpl(SuperClass) 方法。

要将其推向逻辑极端,您可能会:

class AppSuperClass {

public final void print(SuperClass superClass) {
if (superClass is SubClass) {
printImpl((SubClass) superClass);
} else {
printImpl(superClass);
}
}

protected void printImpl(SuperClass superClass) {
...
}

protected void printImpl(SubClass subClass) {
...
}
}

AppSubClass 将仅覆盖 printImpl(一个或两个重载)。

编辑:如评论中所述,另一种方法是使用 Visitor pattern 。这不是我非常喜欢的模式,但是如果你可以修改SuperClassSubClass来了解AppSuperClass(或其实现的接口(interface))它可以为您工作。

关于Java - 重载和覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6774210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com