tuskiomi tuskiomi - 29 days ago 9
Java Question

Java- variable that's static, but extended subclasses don't share the value

Let's say I have a class:

public abstract class Foo{
public static int i = 0;
}


I want to make it so that when I have 2 additional classes like so:

public class Bar extends Foo{
public Bar(){ i=1; }
}


and

public class t extends Foo{
public t(){ i=-1;}
}


that Bar.i, and t.i are not the same value, but rather static to their respective sub classes.

how is this done properly?

Here is a better example:



say I have a class:

public abstract class vehicle{
public static int tires;
}


and I have two sub classes:

public class car extends vehicle{
public car(){
//ALL cars have 4 tires. this is static to cars.
tires = 4;
}
}


and

public class motorcycle extends vehicle{
public motorcycle(){
//All motorcycles have 2 tires. this is static to motorcycles.
tires = 2;
}
}


Obviously, cars and motorcycles do NOT have the same number of Tires, yet I still want to be able to access both car.tires and motorcycle.tires, returning 4 and 2 respectively. I would also like to have the ability to call {variableName}.tires, given that the variable is a vehicle. I would also like to have the ability to add more variables like this later, an example being another int
numberOfLights
.

Answer

They do share the value, though. Example

// All print 0
System.out.println(Foo.i);
System.out.println(Bar.i);
System.out.println(T.i);

new Bar(); // all print 1
System.out.println(Foo.i);
System.out.println(Bar.i);
System.out.println(T.i);

new T(); // all now print -1
System.out.println(Foo.i);
System.out.println(Bar.i);
System.out.println(T.i);

Either you want a variable in each class, or you actually want instance variables, not class variables.

UPDATE

As for your better example, you want abstract methods, not static variables.

abstract class Vehicle {
    public abstract int getTires();
}

class Car extends Vehicle {
    @Override
    public int getTires() { return 4; }
}

class Motocycle extends Vehicle {
    @Override
    public int getTires() { return 2; }
}