File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes default constructor in SuperClass? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "default constructor in SuperClass?" Watch "default constructor in SuperClass?" New topic

default constructor in SuperClass?

Angela Xia

Joined: Jan 03, 2002
Posts: 10
Question ID :957621799662
Consider the following subclass definition:
public class SubClass extends SuperClass
int i, j, k;
public SubClass( int m, int n ) { i = m ; j = m ; } //1
public SubClass( int m ) { super(m ); } //2
Which of the following constructors MUST exist in SuperClass for SubClass to compile correctly?
The answer of this question is:
public SuperClass(int a)
public SuperClass()
I know the first one is absolutely right, but how about the second one? Since SubClass will not call the default constructor in SuperClass, it does it must exist in order to compile fine?

Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
If you don't explicitely call the superclass constructor, the compiler will call it for you, that it
public SubClass( int m, int n ) { i = m ; j = m ; } //1
is rewritten to
public SubClass( int m, int n ) { super();i = m ; j = m ; } //1
by the compiler

[Blog] [Blogroll] [My Reviews] My Linked In
Rick Reumann
Ranch Hand

Joined: Apr 03, 2001
Posts: 281
The thing to remember here is that you have to remember if you provide any other constructors in the super class, than the default constructor is NOT automatically provided. So since super(m) is declared, obviously like you mentioned you must provide that constructor that takes an int, but since you had to provide that constructor in the super class you now must actually declare the constructor with no arguments if you are going to have any code that will implicity call super() like Valentin mentions will happen in the SubClass in the second method.
Sorry if that explanation is not too clear. All the Java cert books cover this topic well.
It is sorta covered in the JavaRanch Style Guide.
subject: default constructor in SuperClass?
Similar Threads
Default constructor
protected constructors
Constructors JQ+