• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Inheritence and Static blocks question

 
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class SubClass extends SuperClass {
static {
System.out.println("Sub class being called");
SuperClass.setS("TREX");
}
}
public class SuperClass {
protected static String s;
static {
System.out.println("Super being called ");
}
static public setS(String t) { s= t; }
static public String getS() { return s; }
}
public static void main(String[] args) {
System.out.println(SubClass.getS());
}
The above prints
"Super being called"
null

Why is "Sub class being called " not printed? It looks like
the subclass static block never gets called.?
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes...The derived class's Static method is not being executed. (Your problem puzzeled me for hours.)
Actually the culprit is static method, you are deriving. The static methods are associated with class they are written in so even though they are accessible in derived class, they actually are executed in/with their own class untill you override them.
If you want your derived class to be loaded, you would need to call atleast one method which is firmly associated with your derived class.

Try this in your sub class.
public class SubClass extends SuperClass {
//just added another static method
public static void someMethod(){
}
static {
System.out.println("Sub class being called");
SuperClass.setS("TREX");
}
}
public static void main(String[] args) {
// calling the new static method, rather than derived one
SubClass.someMethod();
}
Plz Tell me if I am wrong.

------------------
Amit Agrawal,
New Delhi, India.
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This puzzling behaviour is explained in JLS 12.4 - Initialization of Classes and Interfaces.
 
And then the flying monkeys attacked. My only defense was this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic