• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on Constructor  RSS feed

 
Arthur King
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, all, the following code really bothers me.
class Super{
String name;
//1
Super(String s){//2
name =s ;
} }

class Sub extends Super{
String name;
Sub(String s){
name=s;
}
public static void main(String args[]){
Super sup = new Super("First");
Sub sub = new Sub("Second");
System.out.println(sub.name + " " + sup.name);
}
}
i thought it should work fine. actually i got compilation error. if i add a contructor without argument " Super(){}" at //1, it will be working fine. i don't know why as i think there is already a contructor over there at //2; could someone please kindly explain. thanks.
arthur
 
Marilyn de Queiroz
Sheriff
Posts: 9082
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Revised code (that works):

When the Sub constructor runs, if you don't call super with the argument at //3, the compiler will insert super() invisibly. Since you don't have a no arg constructor for Super, you get an error.

[This message has been edited by Marilyn deQueiroz (edited November 04, 2001).]
 
Arthur King
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks, Marilyn deQueiroz, i got it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!