aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Construtors and Static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Construtors and Static methods" Watch "Construtors and Static methods" New topic
Author

Construtors and Static methods

Satish Varma Danthuluri
Greenhorn

Joined: Sep 20, 2006
Posts: 1
Hai All,
Somewhere i have studied that we cannot invoke instance(nonstatic) metohds until after the super constructor has run.

but i have 2 versions of a program one using nonstatic and other using static method. for detail check this code.

public class MyAnimal{
String name;
MyAnimal(String name){
this.name = name;
}
MyAnimal(){
this(makeRandomName());
}
<static> String makeRandomName(){ // the only difference is static
String name = new String[]{"Dog","Cat","Horse","Tiger","Lion"}[(int)(Math.random()*5)];
return name;
}
static public void main(String[] args){
MyAnimal a = new MyAnimal();
System.out.println(a.name);
MyAnimal b = new MyAnimal("abc");
System.out.println(b.name);
}
}

but both the porgrams were working,which shouldn't happen according to the rule.


can anybody help me sorting this out.

thanks in advance
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by Satish Varma Danthuluri:
Hai All,
Somewhere i have studied that we cannot invoke instance(nonstatic) metohds until after the super constructor has run.

but i have 2 versions of a program one using nonstatic and other using static method. for detail check this code.

public class MyAnimal{
String name;
MyAnimal(String name){
this.name = name;
}
MyAnimal(){
this(makeRandomName());
}
<static> String makeRandomName(){ // the only difference is static
String name = new String[]{"Dog","Cat","Horse","Tiger","Lion"}[(int)(Math.random()*5)];
return name;
}
static public void main(String[] args){
MyAnimal a = new MyAnimal();
System.out.println(a.name);
MyAnimal b = new MyAnimal("abc");
System.out.println(b.name);
}
}

but both the porgrams were working,which shouldn't happen according to the rule.


can anybody help me sorting this out.

thanks in advance


But in this case, the superclass is Object. Its constructor is called before the code in the no-argument constructor is run.
James Quinton
Ranch Hand

Joined: Oct 02, 2006
Posts: 94
MyAnimal class's superclass is Object.
you code is same as this:

MyAnimal(String name){
super();
this.name = name;
}
MyAnimal(){
this(makeRandomName());
}

the super() is run before makeRandomName() is invoked;
the rule is that jdk will insert super() into the very first line of the constructor which doesn't have super() or this()
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Construtors and Static methods