I got this code from a text book.
class FirstClass
{
int idNo =25;
public static void print()
{
System.out.println("firstclass citizen " + idNo);
}
}
class SecondClass
{
int idNo =24;
public static void print()
{
System.out.println("secondclass citizen" + idNo);
}
}
public class People
{
//FirstClass female;
//SecondClass male;
public static void main(String[] args)
{
System.out.println("people from java world");
FirstClass.print();
SecondClass.print();
}
}
But when compiling this code I got the following errors
People.java:7: error: non-static variable idNo cannot be referenced from a stati
c context
System.out.println("firstclass citizen " + idNo);
^
People.java:16: error: non-static variable idNo cannot be referenced from a stat
ic context
System.out.println("secondclass citizen" + idNo);
^
2 errors
thisrefer to current Object, you can refer to any member of the current object from within an instance method or a constructor by using this. But you can not usethisreference in static context(method or block).staticmethod can be called without creating object of that class. So if you use this or non-static variable into the static context it will create compilation error.