如果我有一个SubOfParent类(它是Parent的子类)和两个方法:
public static void doStuff(Parent in) {}
public static void doStuff(SubOfPArent in) {}
当我传递SubOfParent类型对象时,为什么第一个doStuff会被调用?
感谢您对此的任何见解!
最佳答案
Parent p = new SubOfParent();
SubOfParent s = new SubOfParent();
doStuff(p); //calls doStuff(Parent in)
doStuff(s); //calls doStuff(SubOfParent in)
//If you're working with a parent but need to call the subclass, you need to upcast it.
dostuff(p as SubOfParent);