Java 扩展示例
我有一个java初学者问题: Parent.print() 在控制台中打印“hallo”, 而且 Child.print() 也打印“hallo”。 我认为它必须打印“孩子”。 我该如何解决这个问题?
public class Parent {
private String output = "hallo";
public void print() {
System.out.println(output);
}
}
public class Child extends Parent {
private String output = "child";
}
i have a java beginner question:
Parent.print() prints "hallo" in the console,
but also Child.print() prints "hallo".
I thought it has to print "child".
How can i solve this?
public class Parent {
private String output = "hallo";
public void print() {
System.out.println(output);
}
}
public class Child extends Parent {
private String output = "child";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
目前您有两个单独的变量,并且
Parent
中的代码仅了解Parent.output
。您需要将Parent.output的值设置为“child”。例如:另一种方法是为父类提供一个构造函数来获取所需的输出:
这实际上取决于您想要做什么。
Currently you've got two separate variables, and the code in
Parent
only knows aboutParent.output
. You need to set the value ofParent.output
to "child". For example:An alternative approach would be to give the Parent class a constructor which took the desired output:
It really depends on what you want to do.
Child
无法访问Parent
的output
实例变量,因为它是私有
。您需要做的就是使其受保护
,并在Child
的构造函数中将output
设置为“child”
。换句话说,两个
output
变量是不同的。如果您将
Parent
中的输出更改为受protected
,您也可以执行此操作:Child
doesn't have access toParent
'soutput
instance variable because it isprivate
. What you need to do is make itprotected
and in the constructor ofChild
setoutput
to"child"
.In other words, the two
output
variables are different.You could also do this if you change output to be
protected
inParent
:child不打印“child”的原因是java中的继承中,只继承方法,而不继承字段。变量
output
不会被子级覆盖。您可以这样做:
此外,字符串变量不需要具有不同的名称,但为了清楚起见,我在这里这样做了。
另一种更易读的方法是这样做:
在本例中,变量是受保护的,这意味着它可以从父级和子级读取。类的构造函数将变量设置为所需的值。这样您只需实现一次打印功能,并且不需要重复的重写方法。
The reason why child is not printing "child" is that in inheritance in java, only methods are inherited, not fields. The variable
output
is not overridden by the child.You could do it like this:
Also, the String variables do not need to be different names, but I did so here for clarity.
Another, more readable way would be to do this:
In this example the variable is
protected
, meaning it can be read from both the parent and child. The constructor of the classes sets the variable to the desired value. This way you only implement the print function once, and do not need a duplicate overridden method.当我试图找出扩展关键字时,我使用了两个类。我希望这也能帮助您理解基本概念。
父类.java
子类.java
When I was trying to figure out the extend keyword, I was using two classes. I'll hope that also will help you to understand the basic idea.
Parent.java
Child.java