Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about protected n static

 
ming ming
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello, why when i put static in a method i can't access to the protected method, but when i take away the static i can..below is the code...

package certification;

public class Parent {
protected int x=9;
}

package other;
import certification.Parent;
public class Child extends Parent{
public static void main(String[] args) {

}
public static void shpw(){ //Over here when i remove this static it works..why?
System.out.println(x);
}
}
 
Sreeraj Harilal
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static methos cannot access non-static variable.
 
Terry Huang
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for the "proteced int x=9" to be initialized, the constructor must be called (in other words, the object must be created). A static method however can be accessed without having the object be created. So if you call a static method that has a instance variable, what value will that variable hold in the method? That is why the compiler doesn't allow you to use non-static variables in static methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic