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)
If
ChildClass
extends fromParentClass
, you can dobut not the other way around.
The left hand side of this declaration is placing a variable named
obj
of declared or static typeParentClass
into the current scope. The right hand side is assigning the variable a reference to anew
object of dynamic typeChildClass
. AChildClass
object is being instantiated and assigned to a variable of typeParentClass
.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 callChildClass
methods, you'll need to cast it.