What is a Class Variable?
Answer:
These are variables declared with in a class, outside any method, with the static keyword.
In Java, a class variable (also known as a static variable) is a variable that is declared with the "static" keyword and is associated with a class, rather than an instance of the class. This means that there is only one instance of the class variable shared among all objects of that class. The value of a class variable can be accessed using the class name and the dot operator (.) without creating an instance of the class. Class variables are used to store information that is common to all instances of a class, such as a constant value that is shared among all objects of a class.
Here's an example to illustrate the use of a class variable in Java:
class Circle { static final double PI = 3.14; double radius; double area; void setRadius(double r) { radius = r; area = PI * r * r; } } public class Main { public static void main(String[] args) { Circle circle1 = new Circle(); Circle circle2 = new Circle(); circle1.setRadius(5); circle2.setRadius(10); System.out.println("Circle1: " + circle1.area); System.out.println("Circle2: " + circle2.area); // Accessing the class variable using the class name and the dot operator System.out.println("PI: " + Circle.PI); } }
In this example, the PI
class variable is a constant value that is shared among all instances of the Circle
class. The value of PI
is accessed using the class name and the dot operator (.
) in the setRadius
method to calculate the area of the circle. The result of this program will be:
Circle1: 78.5 Circle2: 314.0 PI: 3.14
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.