Instantiating Objects & the relation of Child/Parent classes

江枫思渺然 提交于 2019-12-11 07:55:08

问题


So, I'm trying to understand some concepts here.

1) The general "syntax" (if you will) of creating a new object. For example, which of the following is "correct" (I know there's more than one way to instantiate an object):

//1) ChildClass obj = new ParentClass();

//2) ParentClass obj = new ChildClass();

I know that the following two are "legal," but I can't understand the difference between instantiating an object when it comes to Child/Parent classes

(I already know that these two are okay):

ChildClass obj = new ChildClass();
ParentClass obj = new ParentClass();

2) Basically, what I'm trying to ask is "Which ClassName refers to the class that the object is instantiated from/on (wording? sorry...), and which ClassName does the object belong to?"

My apologies if this doesn't really make sense. I tried wording it the best I can.

(Some background: I am currently taking the first "course" of Object-Oriented Java)


回答1:


If ChildClass extends from ParentClass, you can do

ParentClass obj = new ChildClass();

but not the other way around.

The left hand side of this declaration is placing a variable named obj of declared or static type ParentClass into the current scope. The right hand side is assigning the variable a reference to a new object of dynamic type ChildClass. A ChildClass object is being instantiated and assigned to a variable of type ParentClass.

In other words, with the variable obj, for the compiler to be happy, you'll only have access to the method declared on its declared type, ie. ParentClass. If you want to call ChildClass methods, you'll need to cast it.

((ChildClass)obj).someChildClassMethod();


来源:https://stackoverflow.com/questions/18863295/instantiating-objects-the-relation-of-child-parent-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!