I have 2 overloaded method, one which runs a superclass and one which runs a subclass. i would expect that when sending a subclass, java would know to run the method specific to the subclass. Alas, it runs the one of the superclass. Here is an example:
public class Test {
static class SuperClass {}
static class SubClass extends SuperClass {}
static void stuff(SuperClass superclass) {
System.out.println("IN 1");
}
static void stuff(SubClass subClass) {
System.out.println("IN 2");
}
public static void main(String[] args) {
SuperClass aClass = new SubClass() ;
stuff(aClass) ;
}
}
I would expect "IN 2" to be printed but instead i get "IN 1"
so i have 2 questions: 1. Why is it happening 2. How do i achieve my wanted result?
Thanks in advance
Why is it happening
Because the overload resolution happens at compile-time, and the compile-time type of the aClass
variable is SuperClass
How do i achieve my wanted result?
Either change the compile-time type of aClass
to SubClass
:
SubClass aClass = new SubClass();
Or cast in the method call:
stuff((SubClass) aClass);
If you want to actually be able to handle any SuperClass
, you should look into overriding instead of overloading, or the visitor pattern / double dispatch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With