Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a class constant?

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?

like image 284
Kyle Avatar asked Nov 12 '15 03:11

Kyle


People also ask

How do you define a class constant?

Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.

What is a class constant Python?

Introduction to Python Class Constants. An unchangeable value, assiged, is called a constant. Meaning, constants are the containers that hold some information and cannot be changed further. Write once, read many times constants are created in the class of Python. Usually, constants are defined in the level of a module.

What is a constant 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 constant in Example?

Constant: A constant can be defined as a fixed value, which is used in algebraic expressions and equations. A constant does not change over time and has a fixed value. For example, the size of a shoe or cloth or any apparel will not change at any point.


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.

like image 194
Elliott Frisch Avatar answered Sep 21 '22 12:09

Elliott Frisch


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.

like image 24
duffymo Avatar answered Sep 25 '22 12:09

duffymo