0

I got into a situation perfectly described in this post(one of the answers) in: is it possible to overload a final method

My question is if there is a way to execute the Derived class method, or another way... It would help a lot in my project to avoid duplicated code just for casting and doing the same operations inside the methods(which are many).

My concern is just to keep the code in one location for maintenance and debugging, and I cant find a way by myself. Thanks in advance.

class Base { public final doSomething(Object o) { System.out.println("Object"); } } class Derived extends Base { public doSomething(Integer i) { System.out.println("Int"); } } public static void main(String[] args) { Base b = new Base(); Base d = new Derived(); b.doSomething(new Integer(0)); d.doSomething(new Integer(0)); } 
2
  • Why is your base method final? It sounds like you want to be able to override it . . . Commented Jul 2, 2014 at 17:51
  • Well, the short answer is that I dont control that part of the code. And the reason is that it have some operations inside that cant be left out if one was to override it.. but it was not my call.. Commented Jul 2, 2014 at 17:54

1 Answer 1

3

The only way to invoke a method overloaded in a child class is to invoke it on a reference of the child class type. You'll need a cast

((Derived) d).doSomething(new Integer(0)); 

which might cause a ClassCastException or invoke it on a variable of the appropriate type

Derived d = new Derived(); d.doSomething(new Integer(0)); 
Sign up to request clarification or add additional context in comments.

1 Comment

That is what I was thinking, well if there is no way, there isn't. thanks for the help anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.