Java – I have a abstract base class and I want to set few properties of base class from sub class. What is the best way to do it ? Make the properties protected ? Create setters in the base class ?
public abstract class A {
protected String tag;
protected String apiUrl;
// Setter
public void setApiUri(String url) {
this.apiUrl = url;
}
}
public class B extends A {
tag = "Class B";
apiUrl = "Class B Prefs";
}
public class C extends A {
tag = "Class C";
apiUrl = "Class C Prefs";
}
Please let me know what is the best approach / any better way of doing it.
If you want maximum encapsulation, make the base class fields private and provide protected accessors. This is usually the best practice.
If you’re not too bothered about maximum encapsulation, you can make the fields protected, but it couples the classes together even more tightly than inheritance does (er) inherently.
In general, your best bet is the first option above. The JVM’s JIT can optimize out the calls, and it helps keep the clases somewhat loosely-coupled.