Java OOP在公共方法定义上定义特定的方法定义
假设我有一个CommonClass
类,它显示所有其他类文件的公共内容:
public class CommonClass {
public static void displayFoo() {
... // printlns here
displaySpecific(); // Among all files made common by this method, I
// want to display something different among the other files
... // printlns here
}
}
我打算这样称呼:
// Filename: fileA.java
public class FileA {
public static void myFunc() {
CommonClass.displayFoo();
// however, I should have a specific definition
// for the displaySpecific()
// method. Should I use interfaces? How should it be structured.
}
// displaySpecific method here
}
另一个文件:
// Filename: fileB.java
public class FileB {
public static void myFunc() {
CommonClass.displayFoo();
// however, I should have a specific definition
// for the displaySpecific()
// method. Should I use interfaces? How should it be structured.
}
// displaySpecific method here
}
等等
主要可能是这个
public class MyMain {
public static void main(String[] args) {
FilaA.myfunc();
System.out.println("");
FileB.myfunc();
System.out.println("");
... and so on...
}
}
这是预期输出:
Common String Common String Common Common Common Common Common
Common Common Common Common Common Common Common
This is File A
Common String Common String Common Common Common Common Common
Common Common Common Common Common Common Common
Common String Common String Common Common Common Common Common
Common Common Common Common Common Common Common
This is File B
Common String Common String Common Common Common Common Common
Common Common Common Common Common Common Common
我该怎么做
# 1 楼答案
如果每个类需要不同的
displayFoo()
定义,那么它们应该是类函数。你对界面的想法可能就是你想要的方式然后,只需在可显示的对象上调用
display()
:然而,在您的示例中,您实际上并不需要接口或其他任何东西,因为您正在调用
myfunc()
,而这反过来又会调用类自己的display()
你可以创建这样的东西:
不太喜欢这种模式,但如果你没有访问原始源代码的权限,或者它们是最终类(我在看你,
java.lang.String
),它可能是更方便的选择