2011-11-05 69 views
-3

假设我有一个CommonClass类,显示的是通用于所有其他类文件:Java的面向对象的定义在一个共同的方法定义一个特定的方法定义

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 

我应该怎么办呢?

+0

而你的问题是...? –

+0

问题编辑..对不起,如果不清楚。 –

+0

为什么要静态函数? – home

回答

1

如果您需要每类的displayFoo()的不同定义,那么它们应该是类功能。你对接口的想法可能是你想要的方式。

public class FileB implements Displayable { 
    public static display() { 
     // Implementation-specific display 
// etc. 

然后你只需要调用display()你的显示对象:

for (Displayable d : displayables) { 
    d.display(); 
} 

在你的榜样,但是,你并不真的需要一个接口或其他任何东西,因为你打电话myfunc()这回合会打电话给班级自己的display()

可以创造这样的事情:

public class DisplayUtil { 
    public static void display(FileA f) { 
     // etc. 
    } 

    public static void display(FileB f) { 
     // etc. 
    } 
} 

不是模式的大风扇,但如果你没有访问原始源,例如,或者他们是final类(我在看你,java.lang.String),它可能是更方便的选择。