Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

about protected n static

 
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);
}
}
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static methos cannot access non-static variable.
 
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.
 
    Bookmark Topic Watch Topic
  • New Topic