This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Construtors and Static methods

 
Satish Varma Danthuluri
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 94
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic