I have an abstract class, for which I want all subclasses to define a constant, based on the implementation- it is mainly metadata about the class implementation.
In the superclass:
protected static final String OBJECT_NAME;
protected static final String OBJECT_DEF;
And then in the subclass:
protected static final String OBJECT_NAME = "awesome class";
protected static final String OBJECT_DEF = "an awesome class that is also great";
Is there a way to force implementations of a class to declare a constant?
Abstract classes can have constants, members, method stubs (methods without a body) and defined methods whereas interfaces can only have constants and methods stubs. Abstract classes can have constructors but interfaces can't have constructors.
Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .
The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class. All the methods in an interface are implicitly abstract unless the interface methods are static or default.
That is, we cannot explicitly construct an object using an abstract class, but we can use it to help construct an object from a subclass. We can treat an abstract class as a superclass and extend it; its subclasses can override some or all of its inherited abstract methods.
This will not work that way. I would define these as abstract functions:
protected abstract String objectName();
protected abstract String objectDef();
And in the subclass:
private static final String OBJECT_NAME = "awesome class";
private static final String OBJECT_DEF = "bla";
protected String objectName(){
return OBJECT_NAME;
}
protected String objectDef(){
return OBJECT_DEF;
}
The methods are not static
, but I think this is the closest you can get to what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With