与Java继承混淆 [英] Confusion with Java inheriting

查看:168
本文介绍了与Java继承混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在阅读一本AP CS考试学习指南,并且我已经了解了最新情况。假设我有一个名为Employee的类,我有另一个继承Employee的类叫做Manager。以下声明之间有区别吗?

I am currently working through an AP CS Exam study guide and I have hit a brick wall in understanding whats going on. Lets say I have a class called Employee and I have another class that inherits Employee called Manager. Is there a difference between the following declarations?

Employee empl1 = new Manager();
Manager empl2 = new Manager();

我基本上对于对象名称之前的术语是什么以及它与新的后期。任何帮助都表示赞赏。

Im basically confused on what the term before the name of the object is doing and how thats different than the term after new. Any help is appreciated.

推荐答案

名称前面的部分是 type 的引用您正在创建的对象。在右侧,在 new 之后,您正在调用一个特定类的构造函数(类 Manager ,在你的例子中)。

The part before the name is the type of the reference to the object that you are creating. On the right side, after the new, you are calling a constructor, of one specific class (the class Manager, in your example).

你可以写

Employee empl1 = new Manager();
Employee empl2 = new Consultant();
Employee empl3 = new Officer();
Employee empl4 = new Secretary();

因为您在那里创建的所有对象都是 Employees 。但是,你不能写

because all of the objects that you are creating there are Employees. However, you could not write

Manager manager = new Secretary();

因为秘书不是经理。

引用的类型(即名称前面的术语)确定您可以使用此引用调用哪些方法。例如,你可以写

The type of the reference (that is, the term before the name) determines which methods you may call using this reference. For example, you could write

Manager manager = new Manager();
manager.doSomethingThatOnlyManagersCanDo();

但你可以

Employee employee = new Manager();
emplyoee.doSomethingThatOnlyManagersCanDo();

因为您只知道对象是员工,但不是经理。 (这是一个经理,但你不知道,因为参考只告诉你它是一个雇员)

because you only know that the object is an employee, but not that is a manager. (It IS a manager, but you don't know it, because the reference only tells you that it is an employee)

这篇关于与Java继承混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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