java – Super()不能在我的extends类上工作

前端之家收集整理的这篇文章主要介绍了java – Super()不能在我的extends类上工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 java的新手,我正在做一个简单的程序,但我不知道为什么我在我的程序中遇到错误,当我尝试使用超级…有人可以解释我或我的错误是什么,因为它不接受super.myCoord()我应该更改或添加什么?
  1. public class myCoord {
  2.  
  3. private double coorX,coorY;
  4.  
  5. public myCoord(){
  6. coorX = 1;
  7. coorY = 1;
  8. }
  9.  
  10. public myCoord(double x,double y){
  11. coorX = x;
  12. coorY = y;
  13. }
  14.  
  15. void setX(double x){
  16. coorX = x;
  17. }
  18.  
  19. void setY(double y){
  20. coorY = y;
  21. }
  22.  
  23. double getX(){
  24. return coorX;
  25. }
  26.  
  27. double getY(){
  28. return coorY;
  29. }
  30.  
  31. public String toString(){
  32. String nuevo = "("+coorX+","+coorY+")";
  33. return nuevo;
  34. }
  35.  
  36. public class Coord3D extends myCoord{
  37. private double coorZ;
  38.  
  39. Coord3D(){
  40. super.myCoord(); // ---> I got an error here !!
  41. coorZ = 1;
  42. }
  43.  
  44. Coord3D(double x,double y,double z){
  45. super.myCoord(x,y); ---> Also here !!
  46. coorZ = z;
  47.  
  48. }
  49.  
  50. void setZ(double z){
  51. coorZ = z;
  52. }
  53.  
  54. double getZ(){
  55. return coorZ;
  56. }
  57.  
  58. }

解决方法

您应该使用点(.)运算符调用方法而不是构造函数.在这里,您使用点(.)调用超类’构造函数.

这就是为什么你会遇到这样的错误

  1. The method myCoord() is undefined for the type myCoord

  1. The method myCoord(double,double) is undefined for the type myCoord

使用这些来调用你的超级构造函数:super();和super(x,y);如下所示.

  1. public class Coord3D extends myCoord {
  2. private double coorZ;
  3.  
  4. Coord3D() {
  5. super(); // not super.myCoord(); its a constructor call not method call
  6. coorZ = 1;
  7. }
  8.  
  9. Coord3D(double x,double z) {
  10. super(x,y); // not super.myCoord(x,y); its a constructor call not method call
  11. coorZ = z;
  12. }
  13. }

猜你在找的Java相关文章