java
Give an example of a class that contains at least one class variable and at least one class method. Explain why using a class variable and method rather than an instance variable and method would be the correct choice in the example you select.
ClassVarTest.java
public class ClassVarTest {
public static int count = 0;
public static void main(String[] args) {
ClassVarTest c1 = new
ClassVarTest();
ClassVarTest c2 = new
ClassVarTest();
c1.increaseCount();
System.out.println(count);
c2.increaseCount();
System.out.println(count);
}
public static void increaseCount(){
count++;
}
}
Output:
1
2
Here the class variable is "count" and class method is "increaseCount()"
Class variable and class methods are nothing but a static variables and static methods.
Class level ariable are accessed by all instance of the same class. It means same memory will be used for each of instance of a class. Some If once instance changes the value of classs variable that value is autmatically effects to the rest of all instances.
In our case, I am increasing count variable value in class method. When we use instance c1 that cout value is 1 and whn we use instance c2 count variable value is 2.
Get Answers For Free
Most questions answered within 1 hours.