1

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)

4

1 回答 1

4

如果ChildClass从 延伸ParentClass,你可以做

ParentClass obj = new ChildClass();

但不是相反。

此声明的左侧是将一个名为obj已声明或静态类型的变量ParentClass放入当前范围。右侧是为变量分配对new动态类型对象的引用ChildClassChildClass正在实例化一个对象并将其分配给类型为 的变量ParentClass

换句话说,使用变量obj,为了让编译器满意,您只能访问在其声明类型上声明的方法,即。ParentClass. 如果要调用ChildClass方法,则需要强制转换它。

((ChildClass)obj).someChildClassMethod();
于 2013-09-18T03:22:31.137 回答