Reputation: 395
SO,letsay we have a bicycle superclass with cadence 0 and 3 subclasses.I want the "trotineta" sbuclass to have cadence 5 while the other 2 subclasses cadence remains 0. Why isnt this working?
class Trotineta extends Bicycle{
Bicycle.cadence = 5;
}
Upvotes: 0
Views: 63
Reputation: 92
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*/
}
// Below is one of the possible solutions
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
}
}
Upvotes: 0
Reputation: 405
You can create getter and setter or just use 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;
}
or
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;
}
}
Upvotes: 1
Reputation: 393771
You haven't shown the definition of Bicycle.cadence
, but based on the syntax, I'm assuming it's a static member. If you change a static member of the base class, all instances of all sub-classes will be affected by this change, since a static member has a single value for all instances of the class.
Now, if cadence
wouldn't be static, you can give it a different value in the constructor of Trotineta
(assuming the sub-class has access to that member).
public Trotineta ()
{
cadence = 5;
}
This would be somewhat wasteful, though, since each instance of Bicycle
would have its own cadence
member.
Upvotes: 2