Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify a method from another class

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.

like image 754
TimeToCode Avatar asked Oct 18 '25 21:10

TimeToCode


1 Answers

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.

like image 114
Sergey Kalinichenko Avatar answered Oct 20 '25 12:10

Sergey Kalinichenko