I would like to create a constant not implemented in super class in order to force subclasses to implement it. The best solution that I've found (on this topic) is to create an abstract method that will return the constant value. I assume that it is impossible to do something like:
abstract final static String Name;
But I still have hope because Java uses something like this in Serializable interface with the serialVersionUID. Did someone know how did they do this? Is it possible to reproduce it in my own class?
Since Java 8, it can have default and static methods also. 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 is a non-access modifier in java applicable for classes, methods but not variables. It is used to achieve abstraction which is one of the pillar of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. Abstract classes.
A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants. A constant can make our program more easily read and understood by others. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance.
A concept or idea not associated with any specific instance. A sketchy summary of the main points of an argument or theory. There is nothing like 'abstract variable' in Java.
Such constant cannot be static
because static
fields are shared among all instances of the class, including instances of all subclasses.
Here is how to implement this as non-static constant:
public abstract class Foo {
public final String name; // Particular value to be defined in subclass
protected Foo (String name) {
this.name = name;
}
}
public class Bar extends Foo {
public Bar () {
super ("Zoo"); // Here we define particular value for the constant
}
}
BTW, serialVersionUID
is not a part of Serializable
interface.
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