简体   繁体   English

通过方法继承重用Java代码

[英]Java code reuse via method inheritance

I am looking for a way to achieve code reuse in Java. 我正在寻找一种在Java中实现代码重用的方法。 A number of classes should have their own (static) data. 许多类应具有自己的(静态)数据。 They should all have a common method, but the method should operate on their own data. 它们都应该有一个通用方法,但是该方法应该对自己的数据进行操作。 The code below returns only "BASE DATA" lines, while the desired output would be BASE DATA, Above1 DATA, Above2 DATA, etc. etc. 下面的代码仅返回“ BASE DATA”行,而所需的输出将是BASE DATA,Above1 DATA,Above2 DATA等。

What is the proper way to achieve this in Java? 用Java实现此目标的正确方法是什么?

public class Base{
  static private String data="BASE DATA";
  static void printData(){System.out.println(data);}

  public static void main(String[] args){
    Base.printData();
    Above1.printData();
    Above2.printData();
    Above3.printData();
  }

}//Base

class Above1 extends Base {
  static private String data="Above1 DATA";
}//Above1

class Above2 extends Base {
  static private String data="Above2 DATA";
}//Above2

class Above3 extends Base {
  static private String data="Above3 DATA";
}//Above3

Use the command pattern (or visitor if you prefer). 使用命令模式(或根据需要访问者)。

The functionality will be inplemented as a command object which is passed to each class. 该功能将作为命令对象进行补充,并传递给每个类。

The class will then execute the command, passing its static data into the command. 然后,该类将执行命令,并将其静态数据传递到命令中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM