To access Static variables we should declare static method inside class.
Static method is designed to call on class name.
Static method is also called as class level method.
Non static method is also called as instance method because it is designed to call on instance.
Since static method is not designed to call on instance, it does not get this reference .
As static method do not get this reference, we can not access non static members in static method directly. Means we access static members inside static methods only.
To access non static members in static method we have to use instance variable.
class Employee{
public int EmpId=1;
public Static String CompanyName=“Vodafone”;
public static void main(String args[])
{
System.Out.Println(“Employee id:”+EmpId); Not Ok
Employee employee=new Employee();
System.Out.Println(“Employee id:”+employee.EmpId); Ok
System.Out.Println(“Company Name:”+CompanyName);
} }
Comments
Post a Comment