JAVATECH NEWS

Java

CORE JAVA

Interview

OFF-CAMPUS

Monday 10 November 2014

can a static method access the non static variable in java?


In this post we will see that access preference of non-static variable by static method.A non-static variable will not allow to be accessed by the static method.For this we have to declare the variable as static by using "static" keyword.

Know more about static variable and non-static variable 

Know more about Static variable and Static methods.

Q.can a static method access the non static variable?
Answer : No.here is an example:
it will show non-static variable x can not be referenced from a static context,if we declare num as static (eg:static int num=10) then it will show the result Value of num is 10.

class Sample
{
  int num=10; //instancre variable
static void test()
{
System.out.print("Value of num is : "+num);
}
}

class StaticDemo
{
public static void main(String args[])
{
Sample.test();
}
}

No comments:

Post a Comment

Designed By Blogger Templates