Is there a way to declare a final attribute in an abstract super class and initialize the value in the sub class?
Thats how you would do it:
public abstract class Location {
private final int locationNumber;
Collection<Figure> visitors;
public Location(int locationNumber) {
this.locationNumber = locationNumber;
}
public int getLocationNumber() {
return locationNumber;
}
}
public class Market1 extends Location {
public Market1() {
super(5);
}
}
public class Market2 extends Location {
public Market2() {
super(10);
}
}
Location m1 = new Market1();
Location m2 = new Market2();
System.out.println(m1.getLocationNumber()); // prints 5
System.out.println(m2.getLocationNumber()); // prints 10
A final class member variable does not need to be initialized when it is declared. It can be assigned a value in the class constructor or in an initialization block.
public abstract class Location {
protected final int locationNumber;
Collection<Figure> visitors;
protected Location(int locNum) {
locationNumber = locNum;
}
public int getLocationNumber() {
return locationNumber;
}
}
public class Market extends Location {
public Market() {
super(5);
}
}
Alternatively, you could make method getLocationNumber
abstract and have each subclass return the relevant value. Then you would not need member locationNumber
.
public abstract class Location {
Collection<Figure> visitors;
public abstract int getLocationNumber();
}
public class Market extends Location {
public int getLocationNumber() {
return 5;
}
}
But if you still want to keep member locationNumber
then the following will also work.
public abstract class Location {
protected final int locationNumber;
protected Location() {
locationNumber = getLocationNumber();
}
public abstract int getLocationNumber();
}
public class Market extends Location {
public int getLocationNumber() {
return 5;
}
}