I am looking for a way to achieve code reuse in 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.
What is the proper way to achieve this in 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
dataneed to be static? Why not make it an instance variable that can be overridden by subclasses? You could always define the actual strings as constants somewhere and then just set your instance variables to those constants.datawere an instance variable,Above1,Above2, andAbove3could all just be instances of the same class, since they're structurally and functionally identical.