1

What would be the best way to achieve testCall2 below without doing explicit parsing (Sub1) in?

class Super {
}

class Sub1 extends Super {
}

class Sub2 extends Super {
}

public void testCall2(Super in) {
    testCall(in);        // <~~~ Compilation Error 

}

public void testCall(Sub1 sub) {

}

public void testCall(Sub2 sub) {

}
3
  • 1
    Which testCall would you like to be invoked? Commented Dec 2, 2014 at 2:43
  • You'll first need to move those methods inside classes to get this to compile. In Java, methods can only exist inside classes. Commented Dec 2, 2014 at 2:48
  • Just one of them, depends on the instanceOf in. However, the point is I don't want to use instanceOf or any explicit casting. Commented Dec 2, 2014 at 2:51

2 Answers 2

2

You'd have to refactor and use polymorphism. Declare the testCall method in Super

class Super {
    public void testCall() {}
}

and implement it in the subclasses.

Then invoke it

public void testCall2(Super in) {
    in.testCall(); 
}

Otherwise you'll have to use a cast to transform the value's type to a type expected by either of the methods.

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

Comments

0

Obviously it will give compile time error because you are creating methods out of class body. your all methods are out of class body..

class Super {
}

class Sub1 extends Super {
}

class Sub2 extends Super {
}// your all three classes are started and ended immediately

public void testCall2(Super in) {
    testCall(in);        // <~~~ Compilation Error 

}

public void testCall(Sub1 sub) {

}

public void testCall(Sub2 sub) {

}
//and all three methods are defined out of any  class body.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.