Instantiating Objects & the relation of Child/Pare

2019-07-24 22:18发布

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条回答
Rolldiameter
2楼-- · 2019-07-24 22:44

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();
查看更多
登录 后发表回答