How do I make the method return type generic?

前端 未结 19 2645
無奈伤痛
無奈伤痛 2020-11-22 06:16

Consider this example (typical in OOP books):

I have an Animal class, where each Animal can have many friends.
And subclasses like

19条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 06:38

    No. The compiler can't know what type jerry.callFriend("spike") would return. Also, your implementation just hides the cast in the method without any additional type safety. Consider this:

    jerry.addFriend("quaker", new Duck());
    jerry.callFriend("quaker", /* unused */ new Dog()); // dies with illegal cast
    

    In this specific case, creating an abstract talk() method and overriding it appropriately in the subclasses would serve you much better:

    Mouse jerry = new Mouse();
    jerry.addFriend("spike", new Dog());
    jerry.addFriend("quacker", new Duck());
    
    jerry.callFriend("spike").talk();
    jerry.callFriend("quacker").talk();
    

提交回复
热议问题