所以,我们有一个自行车超级课程,有节奏0和3子类。我想要" trotineta" sbuclass有cadence 5而其他2个子类cadence仍为0。 为什么这不起作用?
class Trotineta extends Bicycle{
Bicycle.cadence = 5;
}
答案 0 :(得分:2)
您还没有显示Bicycle.cadence
的定义,但根据语法,我假设它是静态成员。如果更改基类的静态成员,则此更改将影响所有子类的所有实例,因为静态成员对于该类的所有实例都具有单个值。
现在,如果cadence
不是静态的,你可以在Trotineta
的构造函数中给它一个不同的值(假设子类可以访问该成员)。
public Trotineta ()
{
cadence = 5;
}
但这会有点浪费,因为Bicycle
的每个实例都有自己的cadence
成员。
答案 1 :(得分:1)
您可以创建getter和setter,也可以只使用word super
public class TestONE extends TestTWO {
{
super.gg = 4;
}
public static void main(String[] args) {
System.err.println(new TestONE().gg);
}
}
class TestTWO {
static int gg = 0;
}
或
public class TestONE extends TestTWO {
public static void main(String[] args) {
TestONE.setGg(5);
System.err.println(new TestTWO().gg);
}
}
class TestTWO {
protected static int gg = 0;
public static int getGg() {
return gg;
}
public static void setGg(int gg) {
TestTWO.gg = gg;
}
}
答案 2 :(得分:0)
class Bicycle{
int cadence = 0;
/* since no access modifier is mentioned, by default cadence becomes
package private ie; it cannot be accessed outside the package
in which it is defined now*/
}
class Trotineta extends Bicycle{
Bicycle.cadence = 5;
/* you cannot do this as cadence is not a static
attribute of class Bicycle*/
}
//以下是可能的解决方案之一
class Trotineta extends Bicycle{
/*below code can also be written in a method but not outside as you have
written in your example code*/
{
this.cadence = 5;
//here 'this' is the current instance of Trotineta
}
}