package 多态;
/**
* 封装:坐标点相关的属性、方法代码
* 封装成Point类
*/
public class Point {
int x;
int y;
/*
* 无参构造方法
*/
public Point() {
}
/*
* 有参构造方法
*/
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public double distance(){
//没有同名局部变量,可以省略this
return Math.sqrt(this.x*x+y*y);
}
public String toString() {
return "("+x+","+y+")";
}
}
package 多态;
public class Point3D extends Point{
int z;
public Point3D(int x,int y,int z){
/**
* 从父类继承的x y
*/
this.x=x;
this.y=y;
this.z=z;
}
@Override
public double distance() {
return Math.sqrt(x*x+y*y+z*z);
}
@Override
public String toString() {
return "("+x+","+y+","+z+")";
}
}
package 多态;
public class TestPoint {
public static void main(String[] args) {
zhuan(new Point(3,4));
//子类对象,转型成父类型传递到zhuan方法
zhuan(new Point3D(3,0, 4));
}
static void zhuan(Point p){
System.out.println(p.toString());
System.out.println(p.distance());
}
}
运行结果
(3,4)
5.0
(3,0,4)
5.0