Understanding inheritance of class variables

后端 未结 2 732
无人共我
无人共我 2021-01-13 19:54

I\'m building a Challenge24Solver class in Java. The logic itself works and finds the solutions as would be expected (with an arbitrary number of arguments). A

相关标签:
2条回答
  • 2021-01-13 20:04

    Static variables are referenced via the class. You have defined operator as being of type Operation, so operator.token refers to Operation.token.

    I recommend using a getter for this purpose:

    abstract Operation { \\ Basic operation class
      abstract public double operate (double x, double y);
      abstract public String getToken();
    }
    
    class AddOp extends Operation {
      public double operate (double x, double y) {
        return x+y;
      }
      public String getToken() {
          return "+";
      }
    }
    
    0 讨论(0)
  • 2021-01-13 20:14

    You cannot make token static in the base class, because then there would be a single token per all inherited classes. You need to make it an instance variable. You cannot even put it in a static method, because static methods in Java are not overridable.

    In Java, variables are not overridable. If you inherit a class and add a variable by the same name, the variable in the derived class will hide, not override the one in the base class.

    To fix this, make token an abstract method in the base, provide an implementation in the derived class, and return the desired value. If you do this, you could replace the abstract class with an interface, because there would be no variables or implementations in it:

    interface Operation { // Basic operation class
        String getToken();
        double operate (double x, double y);
    }
    class AddOp implements Operation {
        public String getToken() {return "+"; }
        public double operate (double x, double y) {
            return x+y;
        }
    }
    

    Alternatively, leave it unassigned in the base, add a constructor that takes the value of the token, and assign it there:

    abstract class Operation { // Basic operation class
        public final String token;
        abstract public double operate (double x, double y);
        protected Operation(String token) {this.token = token; }
    }
    class AddOp extends Operation {
        public AddOp() { super("+"); }
        public double operate (double x, double y) {
            return x+y;
        }
    }
    
    0 讨论(0)
提交回复
热议问题