Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

java - How to override/extend an inner class from a subclass?

I want to change how a method of a class executes without overriding the method, and only overriding (or ideally extending) the inner class. Assume that I cannot change the fact that I need to do this (I am modifying an existing open source code base and there would be friction to pulling out classes or whatnot).

public class A {
  static class Thing {
    public int value() { return 10+value2(); }
    public int value2() { return 10; }
  }

  public String toString() {
    Thing t = new Thing();
    return Integer.toString(t.value());
  }
}

public class B extends A {
  static class Thing {
    public int value2() { return 20; }
  }
}

My goal is, by changing only Thing, getting B's toString() to return "30", where currently it will return "20". The ideal would be to change only the method value2 (thus leaving any other methods unchanged), but I don't know if this is possible.

Thanks

question from:https://stackoverflow.com/questions/7588091/how-to-override-extend-an-inner-class-from-a-subclass

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you need a factory method for this. Consider the following example (derived from your snippet):

static class A {
    static class Thing {
        public int value() {
            return 10 + value2();
        }
        public int value2() {
            return 10;
        }
    }
    protected Thing createThing() {
        return new Thing();
    }
    public String toString() {
        return Integer.toString(createThing().value());
    }
}

static class B extends A {
    static class Thing extends A.Thing {
        public int value2() {
            return 20; 
        }
    }
    @Override
    protected Thing createThing() {
        return new Thing(); // creates B.Thing
    }
}

public static void main(String[] args) {
    System.out.println(new B());
}

Output:

30

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...