aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructor for a subclass. 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 "Constructor for a subclass." Watch "Constructor for a subclass." New topic
Author

Constructor for a subclass.

Thunthu Ganapathy
Greenhorn

Joined: May 09, 2000
Posts: 19
class Complex1 {
public int real, imaginary;
public Complex1 (int r, int i) {
real = r;
imaginary = i;
}
public Complex1 add(Complex1 c) {
return new Complex1 (real + c.real, imaginary + c.imaginary);
}
void Output() {
System.out.println("Values : " + real+" "+imaginary);
//System.out.println("Values c2: " + c2.real+" "+c2.imaginary);//illegal
//System.out.println("Values c3: " + c3.real+" "+c3.imaginary);//illegal
}
}
class subComplex1 extends Complex1 {
subComplex1 (int r, int i) {
real = r;
imaginary = i;
}
}

class Complex2 {
void useThem() {
Complex1 c1 = new Complex1(1,2);
Complex1 c2 = new Complex1(3,4);
Complex1 c3 = c1.add(c2);
c1.Output();
c2.Output();
//c2.Output();
//double d = c3.real;
}
}
class Client {
public static void main (String args[]) {
Complex2 com2 = new Complex2();
com2.useThem();
}
}
While compiling I am getting an error saying that no Constructor matching Complex() found in class Complex1.
Could anyone explain why cann't I have a constructor for a subclass and the usage?.
Thanks,
Thunthu
Nirmala
Ranch Hand

Joined: Jun 28, 2000
Posts: 93
Hi Ganapathy,
CONSTRUCTORS ARE NOT INHERITED
Hope you will get it now!:rolleyes
Regards.
Nirmala
jafarali
Ranch Hand

Joined: Jul 15, 2000
Posts: 37

To avoid comfusions look at the following code :
class Gd {
int x;
/*Gd() {
}*/
Gd(int y) {
x=y;
}
}
class Gdn extends Gd {
Gdn() {
System.out.println("Good boy");
}
public static void main(String args[]){
Gdn x = new Gdn();
}
}
If you didn't put call to super() method inside constructor of subclass, compiler will automatically add a default super() without any argument. And in your code Complex1 doesn't have any constructor without argument. add super(int,int) call in your subComplex1 constructor.
I hope this clear your point
Thunthu Ganapathy
Greenhorn

Joined: May 09, 2000
Posts: 19
Thanks to Nirmala and jafar ali. Could anybody be of more dumb than I am?.
Regards,
Thunthu
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Constructor for a subclass.