Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor for a subclass.

 
Thunthu Ganapathy
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ganapathy,
CONSTRUCTORS ARE NOT INHERITED
Hope you will get it now!:rolleyes
Regards.
Nirmala
 
jafarali
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to Nirmala and jafar ali. Could anybody be of more dumb than I am?.
Regards,
Thunthu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic