San*_*ith 2 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() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
Run Code Online (Sandbox Code Playgroud)
然后我想写B班.
public class B extends A{
private int fee;
private int goals; // something unique to class B
Run Code Online (Sandbox Code Playgroud)
我不明白如何为类B编写构造函数来访问它的私有变量.我写了这样的东西,错了.
B(int fee, int goals){
this.fee= fee;
this.goals=goals;
}
Run Code Online (Sandbox Code Playgroud)
你可以帮我解释一下这个简短的解释.
上面应该没问题,除了你必须指定对A构造函数的调用,因为通过构造a B,你也构造了一个A
例如
public B(int fee, int goals) {
super(someName, someLocation); // this is calling A's constructor
this.fee= fee;
this.goals=goals;
}
Run Code Online (Sandbox Code Playgroud)
在上面你不知何故必须确定如何构建一个A.您指定的值是A多少?您通常会将其传递给B的构造函数,例如
public B(int fee, int goals, String name, String location) {
super(name, location);
this.fee= fee;
this.goals=goals;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |