• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Is it must to call super class constructor?

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This program gives me compile time error.Is it must to call super class constructor?

class Sup{
public Sup(String str){
System.out.println("Super class");
}
}

public class Class1 extends Sup{
public Class1(){
System.out.println("sub class");
}
public static void main(String[] args) {
Class1 t2 = new Class1();
}
}
 
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you extend a class which does not have a no-argument constructor you must indeed call the constructor (using super) explicitly in the constructors of your derived classes.
 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

If you don�t type a constructor into your class code, a default constructor will be automatically generated by the compiler. The default constructor is always a no-arg constructor. If you want a no-arg constructor and you�ve typed any other constructors into your class code, the compiler won�t provide the no-arg constructor for you. In other words, if you�ve typed in a constructor with arguments, you won�t have a no-arg constructor unless you type it in yourself. If you do type in a constructor, and you do not type in the call to super(), the compiler will insert a no-arg call to super() for you.

If your super constructor (that is, the constructor of your immediate superclass/parent) has arguments, you must type in the call to super(), supplying the appropriate arguments. If your superclass does not have a no-arg constructor, you must type a constructor in your class (the subclass) because you need a place to put in the call to super with the appropriate arguments.



Hope this helps..
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic