Search code examples
javaoopabstract-classencapsulation

Overriding Abstract Fields Java


I have an abstract class which has a method used by all classes that extend the class. That method is identical for each class so I don't want to have to write it over and over in those classes. The problem is that the method uses 2 variables that are declared in each class. I can't have the method in the abstract class without having those variables int eh abstract class. But if I do that, they take on the value specified in the abstract class, not the classes that extend it. How can I fix this?

Example code:

public abstract class Example {
   public String property1 = ""
   public String property2 = ""
    public ArrayList<String> getPropertyies() {
        ArrayList<String> propertyList = new ArrayList<>();
        propertyList.add(property1);
        propertyList.add(property2);
        return property1;
    }
}

public class ExampleExtension extends Example {
    public String property1 = "this is the property";
    public String property2 = "this is the second property";
}

Solution

  • You should limit the scope of the fields to private in the abstract class and declare a constructor for populating the values:

    public abstract class Example {
        private final String property1;
        private final String property2;
    
        protected Example(String property1, String property2) {
            this.property1 = property1;
            this.property2 = property2;
        }
        //...
    }
    

    Subclasses would then initialize the field values in their constructors by calling the super constructor:

    public class ExampleExtension extends Example {
    
        public ExampleExtension() {
            super("value1", "value2");
            // initialize private fields of ExampleExtension, if any
        }
        // ...
    }