抽象的抽象方法的部分实现 class
partial implementation of abstract method of an abstract class
我有一个名为 MyAbstractClass 的抽象 class。
我有 5 个不同的 classes 扩展它:classes A,B,..E
我需要在 class MyAbstractClass 中添加方法 foo() 但只有 A, B和C
应该实现它,而 D 和 E 永远不需要执行它。 (程序流不会到那里)
在 Java 中实现此行为的良好做法是什么?
我应该使用界面吗?
是不是要再加一层继承二区分,只在中间层加foo?
感谢任何建议。
我在这里看到三种基本方法:
如果方法被调用childclass什么都不做
在这种情况下,您可以记录调用或调用它的警告,而无需执行任何其他操作。
child class 不应该执行方法
在这种情况下,您可以抛出 UnsupportedOperationException
。
D 和 E 与 [A、B 和 C] 根本不同
如果这三个实现 class 的方式与 D 和 E 不同,请考虑将这三个实现 parent class [=42] =] 你的超级 class。但是,如果所有五个 class 代表相似的概念,这可能没有意义。
为A、B、C制作接口
正如 yuz 和 Eiko 所建议的,您可以为这个只有 A、B 和 C 实现的特定方法创建一个接口。如果你正在处理 superclass 引用类型,你可以检查 if obj instanceof MyInterface
以确定该方法是否应该是 运行.
如果您使用的是 Java 8+,并且 A、B 和 C 的相关方法之间没有功能差异,您可以在接口中定义一个 default
方法,所有实施 classes 可以使用。
I see two approaches:
make default implementation of foo
in the parent class that does nothing (an empty method) not making it abstract. In this case you override the method in descendant classes as needed.
create interface that contains foo
and implement that in A
, B
and C
. In this case you will want to check if an object is implementing the interface having a reference to the object in MyAbstractClass
variable, before you can actually invoke foo
.
我有一个名为 MyAbstractClass 的抽象 class。
我有 5 个不同的 classes 扩展它:classes A,B,..E
我需要在 class MyAbstractClass 中添加方法 foo() 但只有 A, B和C 应该实现它,而 D 和 E 永远不需要执行它。 (程序流不会到那里)
在 Java 中实现此行为的良好做法是什么?
我应该使用界面吗?
是不是要再加一层继承二区分,只在中间层加foo?
感谢任何建议。
我在这里看到三种基本方法:
如果方法被调用childclass什么都不做
在这种情况下,您可以记录调用或调用它的警告,而无需执行任何其他操作。
child class 不应该执行方法
在这种情况下,您可以抛出 UnsupportedOperationException
。
D 和 E 与 [A、B 和 C] 根本不同
如果这三个实现 class 的方式与 D 和 E 不同,请考虑将这三个实现 parent class [=42] =] 你的超级 class。但是,如果所有五个 class 代表相似的概念,这可能没有意义。
为A、B、C制作接口
正如 yuz 和 Eiko 所建议的,您可以为这个只有 A、B 和 C 实现的特定方法创建一个接口。如果你正在处理 superclass 引用类型,你可以检查 if obj instanceof MyInterface
以确定该方法是否应该是 运行.
如果您使用的是 Java 8+,并且 A、B 和 C 的相关方法之间没有功能差异,您可以在接口中定义一个 default
方法,所有实施 classes 可以使用。
I see two approaches:
make default implementation of
foo
in the parent class that does nothing (an empty method) not making it abstract. In this case you override the method in descendant classes as needed.create interface that contains
foo
and implement that inA
,B
andC
. In this case you will want to check if an object is implementing the interface having a reference to the object inMyAbstractClass
variable, before you can actually invokefoo
.