I'm pretty new in java and I'm doing a simple program but I don't know why I get an error in my program when I'm try to use super... Does anybody can explain me or what is my error, because it's not accepting super.myCoord() what should I change or add?
public class myCoord {
private double coorX, coorY;
public myCoord(){
coorX = 1;
coorY = 1;
}
public myCoord(double x,double y){
coorX = x;
coorY = y;
}
void setX(double x){
coorX = x;
}
void setY(double y){
coorY = y;
}
double getX(){
return coorX;
}
double getY(){
return coorY;
}
public String toString(){
String nuevo = "("+coorX+", "+coorY+")";
return nuevo;
}
public class Coord3D extends myCoord{
private double coorZ;
Coord3D(){
super.myCoord(); // ---> I got an error here !!
coorZ = 1;
}
Coord3D(double x, double y, double z){
super.myCoord(x,y); ---> Also here !!
coorZ = z;
}
void setZ(double z){
coorZ = z;
}
double getZ(){
return coorZ;
}
}
Both super and this keywords in Java can be used in constructor chaining to call another constructor. this() calls the no-argument constructor of the current class, and super() calls the no-argument constructor of the parent class.
Your code would break if you called a super of a super that had no super. Object oriented programming (which Java is) is all about objects, not functions. If you want task oriented programming, choose C++ or something else.
Hence, returning super from the object's method will not work, as there's no super-class instance, on the heap, to be returned; If the parent classes are not instantiated, then how the members of the super classes are made available to the child class? are they copied to the derived child classes?
Calling the super
's constructor in Java is done by super()
, either with arguments or without. In your case:
public class Coord3D extends myCoord{
private double coorZ;
Coord3D(){
super();
coorZ = 1;
}
Coord3D(double x, double y, double z){
super(x,y);
coorZ = z;
}
// rest of the class snipped
}
You should call methods, not constructors, using the dot (.
) operator. Here you are calling super class' constructor using dot (.
).
That's why you are getting errors like these:
The method myCoord() is undefined for the type myCoord
and
The method myCoord(double, double) is undefined for the type myCoord
Use these to call your super constructor: super();
and super(x,y);
as shown below.
public class Coord3D extends myCoord {
private double coorZ;
Coord3D() {
super(); // not super.myCoord(); its a constructor call not method call
coorZ = 1;
}
Coord3D(double x, double y, double z) {
super(x,y); // not super.myCoord(x,y); its a constructor call not method call
coorZ = z;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With