In: Computer Science
Java homework question:
Explain how class (static) variables and methods differ from their instance counterparts. 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.
Static variables or methods are class variables where as instance variables and methods belongs to objects. so instance variables will have each copy for the objects
if we use instance methods than you dont need to create an object for the class you can access that method using the instance method
Example:
public class StaticEx {
private int a1;
private int arr[]=new int[10000];
static int count=0;
public static void fun(){
System.out.println("Fun");
}
public static void main(String[] args) {
StaticEx.fun();
}
}
// in the above program I want to call fun
// so to access method if we create a an object lot of memory is
allocated as it has array of 1000 elements
// to call just fun method do we need that much memory ?
// in those cases we will make methods as static so that without
creating object we can access those methods with the class name