1

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
4
  • You can't do it directly. Check this for some hints: stackoverflow.com/questions/5667764/… Commented Dec 13, 2013 at 18:45
  • 1
    Why does data need 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. Commented Dec 13, 2013 at 19:29
  • Going even a step further from @superEb, you don't even multiple classes for this example. If data were an instance variable, Above1, Above2, and Above3 could all just be instances of the same class, since they're structurally and functionally identical. Commented Dec 13, 2013 at 20:27
  • It looks like the workaround suggested by pksiazek will work for me. Data needs to be static (this is just an illustration of the real life problem). Seems like command pattern may not work for two reasons: 1. every Receiver class would have to implement the functionality 2. Command interface, being an interface, does not allow static abstract methods (but I hear that changed in Java 8). Commented Dec 13, 2013 at 23:19

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.