I am told to declare and initialize my class constant. I didn't know what it was so I searched google, apparently everyone already knows what it is and nobody has asked on it. So what is a class constant? Is it just a value that doesn't change throughout the class?

2

2 Answers

JLS-8.3.1.1. static Fields says (in part)

A static field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).

JLS-4.12.4. final Variables says (in part)

A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28)

tl;dr

Putting that together, a class constant is a static final field.

2

Class variables are static; instance variables are not.

Final variables are constant.

So a class constant would be declared like this:

public class Foo { // Class constant public static final String DEFAULT_NAME = "Bar"; public static void main(String [] args) { String name = Foo.DEFAULT_NAME; } } 

It's the same for all instances of Foo.

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy