如何修改另一个方法 class

How to modify a method from another class

我有以下 class 调用 A,方法 getValue():

public class A {
    public final int getValue() {
        return 3;
    }
}

方法getValue()总是returns 3,那我还有一个class称为 B,我需要实现一些东西来访问 class A 中的方法 getValue(),但我需要 return 4 而不是 3.

Class B:

public class B {
  public static A getValueA() {
    return new A();
  }
}

主要classATest:

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class ATest {

    @Test
    public void testA() {
        A a = B.getValueA();
        assertEquals(
            a.getValue() == 4,
            Boolean.TRUE
        );
    }
}

我试图覆盖该方法,但我真的不知道如何获得我想要的。有什么问题post在评论。

您不能覆盖该方法,因为它是 final。如果不是final,你可以这样做:

public static A getValueA() {
    return new A() {
        // Will not work with getValue marked final
        @Override
        public int getValue() {
            return 4;
        }
    };
}

此方法在 B 中创建一个匿名子类,覆盖该方法,并 returns 一个实例给调用者。匿名子类中的覆盖 returns 4,根据需要。

仔细看看您在做什么:您已经为 class B 提供了一个工厂方法来创建 class A 的新实例。但这并没有改变任何东西方法的实现getValue().

试试这个:

从 class 中的方法 getValue() 中删除最终修饰符 A.

然后让classBextend/inheritclassA.

public class B extends A {
  @Override
  public int getValue() {
    return 4;
  }
}

希望这会有所帮助... =)

此致

亚历克斯