Search code examples
javaoopstaticabstract-classsuperclass

Java static members of abstract classes


I have following setup: superclass Vehicle with atribute capacity and two subclasses Bus and Tram. All trams have the same capacity as well as all buses (it should be static attribute), but capacity of a tram may be different from capacity of a bus. How to implement such approach in Java?

I have partially solved the problem just ignoring the fact that capacity should be static attribute for all subclasses (no static attributes).


Solution

  • You should encapsulate the capacity in a getCapacity method. That method can then look for an appropriate static variable for the specific class, so for example:

    abstract class Vehicle {
        public int getCapacity();
    }
    
    class Tram {
    
        private static final int TRAM_CAPACITY = 200;
    
        @Override
        public int getCapacity() {
            return TRAM_CAPACITY;
        }
    }
    
    class Bus {
    
        private static final int BUS_CAPACITY = 100;
    
        @Override
        public int getCapacity() {
            return BUS_CAPACITY;
        }
    }
    

    This has the added bonus that if one day you want to calculate the capacity based on some other property (for example the number of seats on a tram given a single cart capacity multiplied by the number of carts) you can modify getCapacity directly without modifying the client code.

    class Tram {
    
        private static final int CART_CAPACITY = 100;
    
        private int carts;
    
        public Tram(int carts) { this.carts = carts; }
    
        @Override
        public int getCapacity() {
            return CART_CAPACITY * carts;
        }
    }