本文介绍了如何从子类重写/扩展内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改类的方法如何在不覆盖方法的情况下执行,并且只覆盖(或理想地扩展)内部类。假设我无法改变我需要这样做的事实(我正在修改一个现有的开源代码库,并且会有拉动类或其他东西的摩擦)。

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; }
  }
}

我的目标是,只改变Thing,获得B的toString()返回30,目前它将返回20。理想情况是只更改方法value2(因此保持其他任何方法不变),但我不知道这是否可行。

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.

谢谢

推荐答案

我认为你需要一个工厂方法。请考虑以下示例(派生自您的代码段):

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());
}

输出:

30

这篇关于如何从子类重写/扩展内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:49