this 关键字和继承 - Java
好吧,这一直困扰着我。 (双关语?)
忽略变量类型,因为这不是问题
假设您有一个父类,例如带有变量 ISBN 的书籍类。构造函数使用 this.ISBN = bla
设置 ISBN。
现在有儿童班。它有一个构造函数,可以调用其中的父构造函数。首先,构造函数是如何形成的?像这样? :
public kidsBook(ISBN, kidVariable) {
super(ISBN);
this.kidVariable = kidVariable;
}
这样的做法正确吗?如果是这样,就会带来第二个问题:来自父类的 this.ISBN,当在子构造函数中调用父类的构造函数时,this 关键字是否引用子版本的 ISBN?
这真的让我很困惑,我敢打赌我写它的方式表明了这种困惑。
编辑:修复了与问题无关的代码错误。
Ok, so this has been messing with me. (double entendre?)
ignoring variable types since that's not the issue
Lets say you have a parent class, for example a book class, with variable ISBN. The constructor sets ISBN using this.ISBN = bla
.
Now there's a child class. It has a constructor that calls the parent one inside it. First, how is the contructor formed? Like this? :
public kidsBook(ISBN, kidVariable) {
super(ISBN);
this.kidVariable = kidVariable;
}
Is that the right way to do it? If so that brings up the second question: the this.ISBN from the parent class, when the constructor from the parent is called in the child constructor does the this keyword refer to the child's version of ISBN?
It's really been confusing me and I bet the way I wrote it shows that confusion in spades.
Edit: Fixed code mistakes not related to the question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你走在正确的轨道上。你的问题的答案是肯定的。
这是使用正确语法的完整代码的样子
You are on the right track. The answers to your questions are yes and yes.
Here's what the complete code would look like with right syntax
构造函数将是:
现在,您将
isbn
参数从KidsBook
的构造函数传递到其超类的构造函数。该超类的构造函数是:最后,
isbn
实例变量(相当于this.isbn
)等于传入的原始isbn
KidsBook 构造函数。The constructor would be:
Now, you are passing in the
isbn
parameter fromKidsBook
's constructor to the constructor of its superclass. The constructor of that superclass is:In the end the
isbn
instance variable (equivalently,this.isbn
) is equal to the originalisbn
passed into the KidsBook constructor.这里是另一个例子,希望能够澄清 java 继承的一些机制。
Here another example that hopefully clarifies some mechanics of java inheritance.