package day04;
/**
* 静态方法
1) 是属于类的方法
2) 使用类名直接调用, 在本类中可以省略类名
3) 静态方法中"没有" 隐含参数this(super)
3.1 静态方法不能访问当前对象(this)的属性和方法
4) 静态方法经常用于工具方法和工厂方法
与当前对象无关的方法, 使用静态方法
*/
public class Demo02 {
public static void main(String[] args) {
Point p1=new Point(3,4);
Point p2=new Point(6,8);
System.out.println(p1.distance(p2));//5
System.out.println(Point.distance(p1, p2));//5
}
}
class Point{
int x; int y;
public Point(int x, int y) {this.x=x; this.y=y;}
/** 计算当前(this)点到另外(other)一点的距离 */
public double distance(/*Point this*/Point other){
int a = this.x-other.x;int b=this.y-other.y;
return Math.sqrt(a*a + b*b);
}
/** 计算两点(p1, p2)间的距离 */
public static double distance(Point p1, Point p2){
int a=p1.x-p2.x; int b=p1.y-p2.y;
return Math.sqrt(a*a + b*b);
}
}
静态方法
最新推荐文章于 2023-04-04 11:15:24 发布