从父类访问子类方法
我不确定该给这个问题起什么标题,所以如果您有任何想法,我会立即修改它。无论如何,我的问题很简单: 我有一个“用户”类和一个扩展用户的“学生”类;当我使用 User u = new Student()
创建对象时,有没有办法从“Student”类访问方法,即使我将其标记为“User”?我的学生班级中有一个“login()”方法,但是当我尝试使用 u.login() 调用它时,它告诉我对象 User 没有登录方法。这是否意味着要使用我的 Student 类方法,我必须将其声明为 Student s = new Student()
?我希望我的问题很清楚。谢谢大家。
I'm not sure which title to give to this question so if You have any idea I'll modify it right away. Anyway my question is simple:
I have a class "User" and a class "Student" that extends User; when I create the object using User u = new Student()
, is there a way to access the methods from the "Student" class even if I decalred it as a "User"? I have a "login()" method inside my student class but when I try to call it with u.login()
it tells me that there is no method login for the object User. Does that mean that to use my Student class methods I have to declare it as Student s = new Student()
? I hope my question is clear. Thank you all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
即使您有一个 Student 对象类型,您的引用也是 User 类型。您只能访问您的用户引用的方法/字段(非私有)。
想想这个远程电视的比喻:你有一台具有多种功能的电视,比如浏览电视频道、youtube、netflix。但是,您的遥控器只能浏览电视频道,因此您将无法访问 youtube 和 netflix。买一个新的遥控器就可以了。
有效方法:
Student s = new Student()
;login()
方法移至 User 内部。您可能还想在 Student 类中重写此方法以包含 Student 功能。然后,您可以调用u.login()
并且将调用该方法的重写版本,即使对象引用具有 User 类型 (更多信息);((Student) u).login()
(更多信息)。Even though you have a Student object type, your reference is of type User. You will only have access to methods/fields (that are not private) of your User reference.
Think of this remote - tv analogy: you have a tv with multiple functions, like browsing tv channels, youtube, netflix. However, your remote can only browse tv channels, so you will not have access to youtube and netflix. Getting a new remote would work.
What works:
Student s = new Student()
;login()
method inside User. You may also want to override this method inside your Student class to include Student capabilities. Then you can callu.login()
and the overridden version of the method would be invoked even though the object reference has User type (further info);((Student) u).login()
(further info).父类不知道子类的知识。
这里,
User u = new Student()
u 是引用类型User
,它不能调用子方法login()
。A parent class does not have knowledge of child classes.
Here,
User u = new Student()
u is of reference typeUser
which can't invoke child methodlogin()
.