实例化对象& Child / Parent类的关系 [英] Instantiating Objects & the relation of Child/Parent classes

查看:325
本文介绍了实例化对象& Child / Parent类的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我试图理解这里的一些概念。

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

1)一般的语法(如果你愿意)创建一个新的对象。例如,下面哪个是正确的(我知道有多种方法来实例化对象):

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)基本上,我想问的是其中 ClassName 引用对象从/ on(wording?sorry ...)实例化的类,以及对象属于哪个类名

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.

(有些背景:我目前正在学习面向对象的Java的第一个课程)

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

推荐答案

如果 ChildClass 你可以做

ParentClass obj = new ChildClass();

但不是相反。

这个声明的左边是在当前范围中放置一个名为 obj 的变量的声明或静态类型 ParentClass 。右侧是为变量分配动态类型 ChildClass 对象的引用。 ChildClass 对象正在被实例化并分配给 ParentClass 类型的变量。

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.

换句话说,使用变量 obj ,为了让编译器快乐,你只能访问在其声明类型上声明的方法,即。 ParentClass 。如果您要调用 ChildClass 方法,则需要进行投射。

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();

这篇关于实例化对象& Child / Parent类的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆