Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force subclasses to include constant in abstract java class

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?

like image 522
pharma_joe Avatar asked Aug 10 '12 07:08

pharma_joe


People also ask

Can an abstract class contain constants?

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.

Can abstract classes be subclasses java?

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 .

Do subclasses have to implement all abstract methods?

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.

Can subclasses continue to use an abstract class as its superclass?

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.


Video Answer


1 Answers

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.

like image 188
Dahaka Avatar answered Oct 24 '22 23:10

Dahaka