| Author |
sequence of execution
|
umamahesh javvadi
Greenhorn
Joined: Apr 22, 2007
Posts: 7
|
|
hi, i have fundamental doubt regarding sequence of execution. when we run a Java file which is proper sequence order & why? constructor code initializer block static initializer code static methods instance methods can any one please explain clearly... and also one more doubt why this below code giving exception...what are the reasons what modifications are needed public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } } public class Subclass extends Superclass { static Subclass s1=new Subclass(); public Subclass(){ System.out.println("Printed in Subclass constructor"); super.printMethod(); s1.printMethod(); } public void printMethod() { //overrides printMethod in Superclass System.out.println("Printed in Subclass"); super.printMethod(); } public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); } } /*output Printed in Subclass constructor Printed in Superclass. Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.NullPointerException at Subclass.<init>(Subclass.java:6) at Subclass.<clinit>(Subclass.java:2) */ regards & thanks in advanced, J.Uma mahesh
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
You have two queries and you ought to have started two threads. About order of execution, no, that is not the correct order. Static members are executed when the class is loaded; a constructor is not executed until it is called by another method. There is lots more about it in the BCEL project manual. Go to section 2.
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Originally posted by Campbell Ritchie: a constructor is not executed until it is called by another method.
Constructors cannot be called by other methods. Constructors are executed when a new instance of the class is created.
|
Joanne
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
Sorry, Joanne and Umamahesh, it was very sloppy writing wasn't it. Would it be better if I said another method in another class invokes the constructor to create a new instance?
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Not really First the method could be in the same class - main methods often create new instances of the class they are in. Second - the constructor does not create a new instance of an object. Once a new instance is created, the constructor is called to initialise it.
|
 |
 |
|
|
subject: sequence of execution
|
|
|