Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i force java methods to run specific implementations

Tags:

java

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

like image 951
ShinySpiderdude Avatar asked Dec 11 '22 23:12

ShinySpiderdude


1 Answers

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.

like image 200
Jon Skeet Avatar answered Dec 28 '22 07:12

Jon Skeet