【发布时间】:2021-09-01 12:45:21
【问题描述】:
我想在编码和编写干净的代码方面做得更好。 我有一个超类 Document 和子类,例如DocA、DocB、DocC等 每个子类 Document 都有这个单独的属性 egg。路径、编号等 我想在像 printPath() 这样的超类中编写一个方法。我想出了两种方法。
- 覆盖超类(DocA)的属性
- 将元素传递给方法 (DocB)
class Document {
String path;
public String getPathA() {
return path;
}
public String getPathB(String path) {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
class DocumentA extends Document{
String path = "pathA";
DocumentA () {
setPath(this.path);
}
}
class DocumentB extends Document{
String path = "pathB";
public String getPathB(){
return super.getPathB(path);
}
}
有更好/更清洁的方法吗?或者更确切地说,其中一种方式可以吗?
【问题讨论】:
-
从这段代码中并不清楚为什么继承是有用的。或者你想要做什么。老实说,我发现很难理解这一切的目的。
-
如果路径变量是DocumentA和DocumentB中的一个常量,你可以把Document变成一个抽象类并创建一个抽象方法'getPath',然后DocA和DocB只提供实现来返回它们的常量. printPath 方法只会调用 getPath
-
如果超类知道只有子类知道的概念,我不会认为它是一个干净的设计或干净的代码。如果它们只在子类中有意义,请将它们保留在那里。如果它们对所有人都有意义,请将它们拉起并可能覆盖特定行为的方法。
-
为什么需要子类?根据您到目前为止告诉我们的内容,这些子类似乎没有必要。相反,
Document类可以有一个带有 getter/setter 的path,然后 a/b/c 可以是Document类的实例。例如。Document docA = new Document("path/to/a");
标签: java subclass superclass