Which Overloaded Method is Called in Java

后端 未结 5 643
一向
一向 2021-01-30 12:56

I have a basic inheritance situation with an overloaded method in the super class.

public class Person {
    private String name;
    private int dob;
    priva         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-30 13:27

    Problem specific solution

    In some languages parameters are resolved to their dynamic type, but not in java. The compiler already determines at compile time where your getWorkDetail(this); will go. this is of type Person, so getWorkDetail(Person e) is called. In your specific case the solution is quite obvious. As others have already pointed out, you'll need to override getWorkDetail() in the Employee class.

    Resolving methods to their dynamic parameter types

    To solve the general problem of resolving parameter types at runtime, using the instanceof operator should be avoided, as it usually leads to unclean code.

    If you have two different classes, a solution as simple as stated above is no longer possible. In these cases you'll have to use the visitor pattern.

    Consider the following classes:

    public interface Animal {
        default void eat(Food food) {
            food.eatenBy(this);
        }
    
        void eatMeat(Meat meat);
    
        void eatVegetables(Vegetables vegetables);
    }
    
    public class Shark implements Animal {
        public void eatMeat (Meat food) {
            System.out.println("Tasty meat!");
        }
    
        public void eatVegetables (Vegetables food) {
            System.out.println("Yuck!");
        }
    }
    
    public interface Food {
        void eatenBy(Animal animal);
    }
    
    public class Meat implements Food {
        public void eatenBy(Animal animal) {
            animal.eatMeat(this);
        }
    }
    
    public class Vegetables implements Food {
        public void eatenBy(Animal animal) {
            animal.eatVegetables(this);
        }
    }
    

    Which you can call like this:

    Animal animal = new Shark();
    Food someMeat = new Meat();
    Food someVegetables= new Vegetables();
    animal.eat(someMeat);        // prints "Tasty meat!"
    animal.eat(someVegetables);  // prints "Yuck!"
    

    Following the visitor pattern calling Animal.eat will call Food.eatenBy, which is implemented by both Meat and Vegetables. Those classes will call the more specific eatMeat or eatVegetables method, which uses the correct (dynamic) types.

提交回复
热议问题