如何修改另一个类中的方法 [英] How to modify a method from another class

查看:88
本文介绍了如何修改另一个类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下名为A的类,具有方法getValue():

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

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

方法getValue()始终返回 3 ,然后我有另一个名为B的类,我需要实现一些方法才能访问其中的方法getValue()类别为A,但我需要返回 4 .而不是 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();
  }
}

主类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.

推荐答案

您不能覆盖该方法,因为它是final.如果不是final,则可以执行以下操作:

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

此方法在B中创建一个匿名子类,重写该方法,然后将一个实例返回给调用方.匿名子类中的覆盖将根据需要返回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.

这篇关于如何修改另一个类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆