This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

default constructor in SuperClass?

 
Angela Xia
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
HIH
 
Rick Reumann
Ranch Hand
Posts: 281
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic