Java Tutorial Class Variables or Static Variables
Aside from instance variables, we can also declare class variables or variables that belong to the class as a whole. The value of these variables are the same for all the objects of the same class. Now suppose, we want to know the total number of student records we have for the whole class, we can declare one static variable that will hold this value. Let us call this as studentCount.
To declare a static variable,
public class StudentRecord
{
//instance variables we have declared
private static int studentCount;
//we'll add more code here later
}
we use the keyword static to indicate that a variable is a static variable.
So far, our whole code now looks like this.
public class StudentRecord
{
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
private static int studentCount;
//we'll add more code here later
}
Aside from instance variables, we can also declare class variables or variables that belong to the class as a whole. The value of these variables are the same for all the objects of the same class. Now suppose, we want to know the total number of student records we have for the whole class, we can declare one static variable that will hold this value. Let us call this as studentCount.
To declare a static variable,
public class StudentRecord
{
//instance variables we have declared
private static int studentCount;
//we'll add more code here later
}
we use the keyword static to indicate that a variable is a static variable.
So far, our whole code now looks like this.
public class StudentRecord
{
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
private static int studentCount;
//we'll add more code here later
}
Related Post:
Java Tutorial switch statement source codeJava tutorial source code get input from keyboard
Java Tutorial Using JOptionPane to get input
Java tutorial Decision Control Structures: if statement
PHP Tutorial
Java programing source code sample printing characters
Java tutorial if-else statement
C programming sample source code: Sum of 2 numbers
Java Programming Features



