Java 链接继承的构造函数时出错
我刚刚开始学习构造函数和继承java,我能知道我的代码中有什么错误我不能链接Java 链接继承的构造函数时出错,java,Java,我刚刚开始学习构造函数和继承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;
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));
}
}
从基类扩展时,应在子构造函数中调用构造函数,有两种情况: First:父类有一个默认构造函数实现(意味着构造函数没有任何参数),在这种情况下,如果您不调用它,编译器将隐式调用它 例如,在坐标类中:
public Coordinate(){
this.x=x;
this.y=y;
}
如果您不调用它,编译器将在子类中隐式调用它,如:
public Coordinate2(int x,int y){
//Implicitly call
//super();
this.x=x;
this.y=y;
}
Second:您的超类中没有默认构造函数实现,并且没有自定义构造函数(构造函数有参数),那么如果您没有调用它,编译器将不会隐式调用它,您应该显式调用它,如:
public Coordinate2(int x,int y){
super(x,y);
this.x=x;
this.y=y;
}
您没有调用
super(x,y)
,那么“链接”是什么意思?您得到的确切错误是什么?为什么您认为构造函数Coordinate2(int x,int y)
的x和y的参数无关紧要,可以直接使用new Coordinate2()
,而不使用任何参数?然而,这不是调用超类构造函数的方式。