4

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
  • 2
    That method cannot be overriden. It's final. Commented Nov 4, 2016 at 23:11

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@TimeToCode It's already there: copy-paste the function getValueA into your class B, remove final from A's getValue, compile, and it will do what you want. The curly braces after new A () is the body of the anonymous class extending A.
But the method should be final, this is a restriction for the problem :/
What you're asking for is impossible. Given A as you have written it now, someA.getValue() is always going to return 3, and there's nothing you can do about it.
0

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

3 Comments

Yes, its obviously, but i have the restriction that the method in class A should be final always..
Okay, I've to admit, that dasblinkenlight was faster and also has the correct answer...What a shame... =/
@TimeToCode If you need that method to be final, you can't do what you want. Both answers won't work with that method marked final.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.