Static Variables and Methods


Compilation Errors


Error Message Name:

	Error: {primitive type} cannot be dereferenced

Example:

	public static void main(String[] args)
	{ int p = 10;
	  double a = p.log();
	} 

Cause: You are trying to call a static method from another class, but you are not following the conventions of calling a method (you are trying to call the log method from the Math class). Remember, to call a static method, the convention is {class name}.{method name}(parameter). In the above example, you have {parameter}.{method name}

Solution: Please follow the convention when calling static methods. In the example above, log is a method within the Math class. Hence, you would have: double a = Math.log(p);


Error Message Name:

	Error: non-static variable {variable name} cannot be referenced from a static context

Example:

	private int magic = 1234;
        private static boolean checkNum(int num)
        {  return magic == num;
	}

Cause: Recall, static methods can access only other static methods or variables. This is because they do not require instantiation, whereas non-static methods and variables need to be instantiated first.

Solution: You have to make the method non-static:

	private int magic = 1234;
	private boolean checkNum(int num)
	{  return magic == num;
	}