|
We have just learned about:
|
In this webpage, we will discuss the class variables
Specifically:
|
|
|
Example:
public class ClassVar1
{
public static double a; // <----- Class variable
************* Skip the rest of the program for now **************
public static void main(String[] args)
{ // Body of method "main"
ClassVar1.a = 3.1415;
System.out.println( ClassVar1.a );
}
}
|
Comments:
|
nameOfClass.nameOfClassVariable
|
public class ClassVar1
{
public static double a; // <----- Class variable
public static void main(String[] args)
{ // Body of method "main"
ClassVar1.a = 3.1415; // Accessing a class variable
System.out.println(a);
}
}
|
How to run the program:
|
|
|
Example:
public class ClassVar2
{
public static double a; // <----- Class variable
public static void main(String[] args)
{ // Body of method "main"
a = 3.1415; // We can omit the classname in this method
System.out.println(a);
}
}
|
How to run the program:
|
|
In other words:
|
|
|
public class ClassVar3x
{
public static void print()
{
System.out.println( ClassVar3x.a ); // Can be access here, even though
// the definition appears below !
}
public static double a = 3.1415; // Class variable "ClassVar3x.a"
}
|
How to run the program:
|
|
Example:
public class ClassVar2
{
public static double a; // <----- Class variable
public static void main(String[] args)
{ // Body of method "main"
a = 3.1415; // We can omit the classname in this method
System.out.println(a);
}
}
|
|
public class ClassVar4
{
public static double a = 3.1415;
public static void main(String[] args)
{
System.out.println( a ); // prints 3.1415 ... (1)
{
String a = "abc"; // Class var a is not accessible ...(2)
// inside inner scope
System.out.println( a ); // prints "abc" ...(3)
System.out.println( ClassVar4.a ); // prints 3.1415 ...(4)
} ...(5)
System.out.println( a ); // prints 3.1415 ...(6)
boolean a = true; // Class var a is not accessible ...(7)
// in main any longer !!!
System.out.println( a ); // prints true ...(8)
System.out.println( ClassVar4.a ); // prints 3.1415 ...(9)
}
}
|
Explanation:
|
How to run the program:
|
|
|
The instance variables will be discussed under the Section User-defined types.