Local database reading edition
How does the compiler handle constructors?
Reconstructed from database records, not a captured original forum layout. Dates and display names are retained as recorded; timezone and real-world identity are not inferred. Historical advice, contact details and offers are not current. Original markup is shown as inert text.
Forum index · Java - Tips Of The Day
Opening post
Asha · 2001-04-27 14:52:05
If, when defining a class, we don't define its constructor, the compiler implicitly assigns one. However, if we do define a constructor, the compiler interprets this as function overriding and does not flash an error. But if this is the case, why do I receive a compiler error in example 3 below?
<pre id=code><font face=courier size=2 id=code>
Example 1:
class x {
int x,y;
public void x( ) { // The compiler considers this method overriding.
}
}
public static void main(String arg[]) {
x x1=new x() // No error.
}
</font id=code></pre id=code>
<pre id=code><font face=courier size=2 id=code>Example 2:
class x {
int x,y;
public x( ) { // The compiler considers this method overloading.
}
public x( int a, int b ) { // The compiler considers this method overloading.
x = a;
y= b;
}
}
public static void main(String arg[])
{
x x1=new x() // No error
x x1=new x( 5, 6 ) // No error
}</font id=code></pre id=code>
<pre id=code><font face=courier size=2 id=code>Example 3:
class x {
int x,y;
public x( int a, int b ) {
x = a;
y= b;
}
}
public static void main(String arg[])
{
x x1=new x() // Why is there an error here?
x x1=new x( 5, 6 ) // No error
}
</font id=code></pre id=code>
First, if you do not define any constructors, Java will insert a default no-arguments constructor of the form:
<pre id=code><font face=courier size=2 id=code>public \(){
super();
}</font id=code></pre id=code>
Second, if you declare constructors, what you see is what you get. This means that if you don't explicitly declare a no-arguments constructor but declare some other constructor, you will only get the constructor that you do explicitly define. This is why you see an error in example 3. Since you've never declared a no-arguments constructor but did define another type of constructor, Java does not insert a no-arguments constructor.
For example 3 to work you must also explicitly declare the no-arguments constructor:
<pre id=code><font face=courier size=2 id=code> public x(){
super();
}</font id=code></pre id=code>
Asha Balasubramanyan
http://www.ammu.org
Edited by - asha on April 27 2001 2:55:00 PM
Source notes
MyCommunity/nandighosha.org.zip!/forum/tools/snitz_forums_2000.mdb
Table: FORUM_TOPICS + FORUM_REPLY · record IDs: 142