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: 2341
posted
0
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
posted
0
MyAnimal class's superclass is Object. you code is same as this:
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()