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

Construtors and Static methods

 
Satish Varma Danthuluri
Greenhorn
Posts: 1
  • 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: 2409
  • 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
  • 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()
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic