• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Question on Constructor  RSS feed

 
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
 
Sheriff
Posts: 9087
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!