Parent obj = new Child();有道理? [英] Does Parent obj = new Child(); make sense?
问题描述
在Java中:
Parent obj = new Child();
我创建了一个类型为Parent的对象.我假设我只能调用Parent类中定义的方法.因此,我无法调用Child中定义的其他"方法或访问Child中定义的变量. 因此,我认为这是浪费内存,因为我新建了一个Child实例,该实例比Parent占用更多的内存空间.至此,我认为这没有任何意义. 任何人都可以请问一些有意义的理由/例子吗?
I created an object of type Parent. I assume that I can only invoke the methods defined in Parent class. Thus, I can't invoke the "additional" methods defined in Child or access variables defined in Child. So I think it's a waste of memory since I have newed a instance of Child which takes additional memory space than Parent. To this point I think it does not make sense. Can anyone please give some reason/example where this make sense?
推荐答案
是的,确实有道理.
如果要使用Child,可以这样做,但是将与它的交互限制为Parent
方法.
You would do this if you want to use a Child, but constrain your interaction with it to Parent
methods.
这种习语在Java集合中尤为常见:
This idiom is particularly common with Java collections:
List<String> myList = new ArrayList<String>();
这篇关于Parent obj = new Child();有道理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!