Java 当类从抽象类扩展时,如何访问其私有变量?
我有一个抽象类Java 当类从抽象类扩展时,如何访问其私有变量?,java,constructor,abstract-class,Java,Constructor,Abstract Class,我有一个抽象类A,而类B就是从它扩展而来的。我将这些变量设置为私有的,并且很好 public abstract class A { private String name; private String location; public A(String name,String location) { this.name = name; this.location = location; } public String getName() {
A
,而类B
就是从它扩展而来的。我将这些变量设置为私有的,并且很好
public abstract class A {
private String name;
private String location;
public A(String name,String location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
然后我想写B类
public class B extends A{
private int fee;
private int goals; // something unique to class B
我不明白如何为类B编写构造函数来访问它的私有变量。
我写了这样的东西,它是错误的
B(int fee, int goals){
this.fee= fee;
this.goals=goals;
}
你能用一个简短的解释来帮我解决这个问题吗。上面应该没问题,只是你必须指定对
a
的构造函数的调用,因为通过构造B
,你也在构造a
e、 g
在上面,您必须以某种方式确定如何构造A
。您将为A
指定哪些值?您通常会将其传递到B.g.的构造函数中
public B(int fee, int goals, String name, String location) {
super(name, location);
this.fee= fee;
this.goals=goals;
}
类
a
没有默认构造函数。这意味着您必须指定从B
构造函数调用a
构造函数
public B(String name, String location int fee, int goals) {
super(name, location); // this line call the superclass constructor
this.fee = fee;
this.goals = goals;
}
如果一个类继承了另一个类,那么在构造子类时,也会隐式调用母类构造函数。
由于
A
没有默认构造函数,这意味着您要使用特定的构造函数,因此必须显式调用它。错误消息解释了问题所在。阅读它。它没有错,问题是因为在构造B类之前,您需要先构造父类,所以您需要调用super(名称、位置)先在B构造函数上构造父级。谢谢朋友们的帮助:)现在我非常理解了well@SanukaHasith你可以通过投票来表达你的感谢:)谢谢,布莱恩,现在我明白了,现在它工作得很好。非常感谢,非常感谢,安东尼,现在我明白了。
public B(String name, String location int fee, int goals) {
super(name, location); // this line call the superclass constructor
this.fee = fee;
this.goals = goals;
}