This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

init blocks example

 
Vidya sumanasekara
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



out put:-
Staticblock Parent
Staticblock Parent 2
Exception in thread "main" java.lang.NoSuchMethodError: main


Help me to understand this output....
 
kurt hanni
Ranch Hand
Posts: 140
Eclipse IDE Java Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are running Parent class, you dont have a main method in your Parent class
 
kurt hanni
Ranch Hand
Posts: 140
Eclipse IDE Java Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
- remove public in Parent class
- make Child class public
- rename file to Child.java
- compile Child.java
- run Child
 
Vidya sumanasekara
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
kurt hanni wrote:You are running Parent class, you dont have a main method in your Parent class



yes .... Thanks..

Then output:-

Staticblock Parent
Staticblock Parent 2
Staticblock Child
Initblock Parent
Constructor Parent
Initblock Child
Initblock Child 2
Constructor Child A
Constructor Child

Can you explain me....
 
Ikpefua Jacob-Obinyan
Ranch Hand
Posts: 394
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vidya sumanasekara wrote:
kurt hanni wrote:You are running Parent class, you dont have a main method in your Parent class



yes .... Thanks..

Then output:-

Staticblock Parent
Staticblock Parent 2
Staticblock Child
Initblock Parent
Constructor Parent
Initblock Child
Initblock Child 2
Constructor Child A
Constructor Child

Can you explain me....
Hello Vidya, study the following VERY carefully, I hope it helps:

1. INIT BLOCKS EXECUTE IN THE ORDER THEY APPEAR

2. STATIC INIT BLOCKS RUN "ONLY ONCE" WHEN THE CLASS IS "FIRST" LOADED BY THE JVM

3. INSTANCE INIT BLOCKS RUN "EACH TIME" A CLASS IS INSTANTIATED

4. INSTANCE INIT BLOCKS RUN "IMMEDIATELY AFTER" THE CONSTRUCTORS CALL TO super()

With the above explanation you can see that the other of execution is:

1. Static init block
2. Instance init block
3. Constructors
[/quote
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic