Search code examples
javasubclassfinalsuperclass

Is there a way to declare a final attribute in an abstract super class and initialize the value in the sub class?


I'd like to have an abstract super class Location with a final attribute locationNumber. But the locationNumber should be initialized in the subclass itself like Market or Mosque. Is there a clean way to do it? I know that it's not going to work like this, it's just to show the problem.

public abstract class Location {
    protected final int locationNumber;
    Collection<Figure> visitors;

    public int getLocationNumber() {
        return locationNumber;
    }
}

public class Market extends Location {
    locationNumber = 5;
}

public class Mosque extends Location {
    locationNumber = 10;
}

Solution

  • 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