我刚开始学习构造函数和继承java,我能否知道我的代码中存在哪些错误,我无法链接Coordinate2
?
这是我的代码:
import java.util.Scanner;
class Coordinate {
protected int x;
protected int y;
public Coordinate() {
}
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
class Coordinate2 extends Coordinate {
public Coordinate2(int x, int y) {
this.x = x;
this.y = y;
}
public float distance(Coordinate2 c) {
float dist;
dist = (float)
Math.sqrt(Math.pow((c.getX() - this.x), 2) +
Math.pow((c.getY() - this.y), 2)
);
return dist;
}
}
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Coordinate2 c1 = new Coordinate2();
System.out.println("enter x point");
c1.setX(input.nextInt());
System.out.println("enter y point");
c1.setY(input.nextInt());
Coordinate2 c2 = new Coordinate2();
System.out.println("enter x point");
c2.setX(input.nextInt());
System.out.println("enter y point");
c2.setY(input.nextInt());
System.out.printf("the value in c1 are(%d,%d)\n", c1.getX(), c1.getY());
System.out.printf("the value in c2 are(%d,%d)\n", c2.getX(), c2.getY());
System.out.printf("the value in c1 and c2 are %2f.\n", c1.distance(c2));
}
}
答案 0 :(得分:1)
当您从基类扩展时,您应该在子构造函数中调用构造函数,并且您有两种情况:
第一个:父类有一个默认的构造函数实现(意味着没有任何参数的构造函数),在这种情况下,如果你没有调用它,编译器将隐式调用它
示例,在您的Coordinate类中:
public Coordinate(){
this.x=x;
this.y=y;
}
如果您不打电话,编译器会在您的子课程中隐式调用它,例如:
public Coordinate2(int x,int y){
//Implicitly call
//super();
this.x=x;
this.y=y;
}
第二:你没有超级默认构造函数实现,并且有一个自定义构造函数(构造函数有参数),如果你没有&#39,编译器就不会隐式调用它;打电话给你,你应该明确地称之为:
public Coordinate2(int x,int y){
super(x,y);
this.x=x;
this.y=y;
}