Abstract variables in Java?
Define a constructor in the abstract class which sets the field so that the concrete implementations are per the specification required to call/override the constructor.
E.g.
public abstract class AbstractTable {
protected String name;
public AbstractTable(String name) {
this.name = name;
}
}
When you extend AbstractTable
, the class won't compile until you add a constructor which calls super("somename")
.
public class ConcreteTable extends AbstractTable {
private static final String NAME = "concreteTable";
public ConcreteTable() {
super(NAME);
}
}
This way the implementors are required to set name
. This way you can also do (null)checks in the constructor of the abstract class to make it more robust. E.g:
public AbstractTable(String name) {
Objects.requireNonNull(name, "Name may not be null");
this.name = name;
}
I think your confusion is with C# properties vs. fields/variables. In C# you cannot define abstract fields, even in an abstract class. You can, however, define abstract properties as these are effectively methods (e.g. compiled to get_TAG()
and set_TAG(...)
).
As some have reminded, you should never have public fields/variables in your classes, even in C#. Several answers have hinted at what I would recommend, but have not made it clear. You should translate your idea into Java as a JavaBean property, using getTAG(). Then your sub-classes will have to implement this (I also have written a project with table classes that do this).
So you can have an abstract class defined like this...
public abstract class AbstractTable {
public abstract String getTag();
public abstract void init();
...
}
Then, in any concrete subclasses you would need to define a static final variable (constant) and return that from the getTag()
, something like this:
public class SalesTable extends AbstractTable {
private static final String TABLE_NAME = "Sales";
public String getTag() {
return TABLE_NAME;
}
public void init() {
...
String tableName = getTag();
...
}
}
EDIT:
You cannot override inherited fields (in either C# or Java). Nor can you override static members, whether they are fields or methods. So this also is the best solution for that. I changed my init method example above to show how this would be used - again, think of the getXXX method as a property.