How to modify a method from another class

我们两清 提交于 2019-12-11 02:40:04

问题


I have the following class called A, with the method getValue():

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

The method getValue() always returns 3, then i have another class called B, i need to implement something to access to the method getValue() in the class A, but i need to return 4 instead 3.

Class B:

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

The main class ATest:

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

I tried to override the method, but really i dont know how to get what i want. Any question post in comments.


回答1:


You cannot override the method, because it is final. Had it not been final, you could do this:

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

This approach creates an anonymous subclass inside B, overrides the method, and returns an instance to the caller. The override in the anonymous subclass returns 4, as required.




回答2:


Take a closer look at what you're doing: You've given the class B a factory method to create a new instance of class A. But this is not changing anything on the implementation of the method getValue().

Try this:

Remove the final modifier from method getValue() in class A.

Then let class B extend/inherit class A.

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

Hope this will help... =)

Best regards

Alex



来源:https://stackoverflow.com/questions/40432938/how-to-modify-a-method-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!