• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

One question about constructor

 
Ling Mike
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote the java code as follow.
----------------------------
class Parent{
Parent(int i){
System.out.println("Constructor in Parent with one argument!");
}
}

class Child extends Parent{
Child(int i){
//super(i);
System.out.println("constructor in child with one argument!");
}
Child(){
System.out.println("constructor in Child without argument!");
}
Child(int i, int j){
System.out.println("constructor in Child with two arguments!");
}
}
----------------------------
There are compile error with subclass's constructor.
Would somebody can tell me why?

And if I add the default constructor in the Parent class, ther will no error. Why?

Thanks!
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Frm Child constructor always first call is no-arg constructor of superclass. Since u have already declared one constructor in parent, compiler will not create a default no-arg for u.

Either
1. comment Parent class constructor
or
2. add no-arg constructor.


Naseem
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Naseem Khan:
Frm Child constructor always first call is no-arg constructor of superclass...

...unless the first line of the Child constructor is an explicit call to another Child constructor (using "this") or an explicit call to a Parent constructor (using "super"). In other words, it's only when one of these explicit calls is absent that an implicit call is made to the no-args superclass constructor.

And as Naseem pointed out, a no-args constructor is automatically provided by the compiler only if no other constructors are explicitly written into the class.
[ May 17, 2006: Message edited by: marc weber ]
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah you are absolutely right marc.

Thanks for correcting me.

Naseem
 
Ling Mike
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see!
Thanks very much!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic