aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes One question about constructor 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 "One question about constructor" Watch "One question about constructor" New topic
Author

One question about constructor

Ling Mike
Greenhorn

Joined: May 17, 2006
Posts: 9
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

Joined: Apr 25, 2005
Posts: 809
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


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
Yeah you are absolutely right marc.

Thanks for correcting me.

Naseem
Ling Mike
Greenhorn

Joined: May 17, 2006
Posts: 9
I see!
Thanks very much!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: One question about constructor