不知道为什么我写的这个重载方法用不了,求解惑
代码和报错原因如下:
package com.wkcto;
import java.lang.Math;
class Point2D{
int x,y;
//构造方法
public Point2D(int x,int y){
this.x=x;
this.y=y;
}
public Point2D(){};
}
class Point3D extends Point2D{
int z;
public Point3D(int x,int y,int z){
super(x,y);
this.z=z;
}
//构造方法
public Point3D(Point2D p,int z){
x=p.x;
y=p.y;
this.z=z;
}
}
public class experiment7_2 {
public static void main(String[] args) {
Point2D p2d1=new Point2D(3,4);
Point2D p2d2=new Point2D(5,5);
System.out.println("平面两点的距离为:"+ Sqrt(p2d1,p2d2));
Point3D p3d1=new Point3D(3,4,5);
Point3D p3d2=new Point3D(p2d2,5);
Sqrt(p3d1,p3d2);
}
double Sqrt(Point2D a,Point2D b){
int x1=a.x-b.x;
int y1=a.y-b.y;
double n=x1*x1+y1*y1;
return Math.sqrt(n);
}
double Sqrt(Point3D a,Point3D b) {
int x1 = a.x - b.x;
int y1 = a.y - b.y;
int z1 = a.z - b.z;
double n = x1 * x1 + y1 * y1 + z1 * z1;
return Math.sqrt(n);
}
}
1.静态方法中只能直接使用静态资源
2.除静态方法外,其他方法需要通过对象调用
你的问题
1.对静态使用不了解
2.对对象使用不了解
多多学习
跟重载没关系,不是都写了吗?cannot be referenced from a static context,看不懂的话找个翻译软件翻译一下。
也就是说你调用的这个方法不是静态方法,要么把这个方法加上static,要么就new experiment7_2().Sqrt(obj1, obj2);
因为不是static的,static方法,只能调用static修饰的方法和变量,如果想在static方法里面调用非static的方法和变量,必须先创建对象,然后通过对象去调用方法或者变量。
experiment7_2 = new experiment7_2();
experiment7_2.Sqrt才可以
1、两个方法的入参是一样的,重写失败
有用望采纳