Suppose I have a CommonClass class that displays what is common to all others class files:
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
}
}
I intend to call that like this:
// 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
}
Another file:
// 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
}
and so on…
Main could be this…
public class MyMain {
public static void main(String[] args) {
FilaA.myfunc();
System.out.println("");
FileB.myfunc();
System.out.println("");
... and so on...
}
}
This is the intended output:
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
How should I do that?
If you need different definitions of
displayFoo()per-class then they should be class functions. Your idea of an interface is probably the way you want to go.Then you just call
display()on your displayable objects:In your example, however, you don’t really need an interface or anything else, because you’re calling
myfunc()which in turn would call the class’s owndisplay().You could create something like this:
Not a big fan of the pattern, but if you don’t have access to the original source, for example, or they’re final classes (I’m looking at you,
java.lang.String), it may be the more-convenient option.