Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract constant in java

Tags:

java

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?

like image 722
Julien Maret Avatar asked Mar 19 '19 10:03

Julien Maret


People also ask

Can abstract class have constants in Java?

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.

What is an abstract variable in Java?

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.

What are constants in Java?

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.

What is an abstract variable?

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.


1 Answers

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.

like image 98
Mikhail Vladimirov Avatar answered Sep 18 '22 12:09

Mikhail Vladimirov