java 数据相加--泛型接口的实现
题目要求:数据往往具有相加的功能,但是对于不同具体类型,相加的含义有所不同,比如复数的相加的结果依然是一个复数,其实部为两个实部之和、虚部为两个虚部之和。而圆相加的结果依然是圆,其圆心为两个圆心的中点,而半径为两个半径之和。要求定义一个具有“相加”的泛型接口。
解题思路:
定义一个规范的泛型接口
复制之前的代码 实现接口的功能
改写toString实现输出 不同类型的相加结果
package _05_第五章泛型.E202_05_02_数据相加;
public class Test {
public static void main(String[] args) {
Point p1 = new Point(1,1);
Point p2 = new Point(3,2);
Circle circle = new Circle(p1,2);
Circle circle2 = new Circle(p2,3);
System.out.printf("两个 圆 相加结果:\n");
System.out.println(circle2.add(circle));
Complex complex = new Complex(1,1);
Complex complex2 = new Complex(2,2);
System.out.printf("两个 复数 相加结果:\n");
complex2.Print(complex2.add(complex));
}
}
package _05_第五章泛型.E202_05_02_数据相加;
public interface Add<T> {
public T add(T t);
}
package _05_第五章泛型.E202_05_02_数据相加;
public class Circle implements Add<Circle> {
private Point p;//圆心
private float r;//半径
public Circle(Point p, float r) {
this.p = p;
this.r = r;
}
public Circle add(Circle circle2){
circle2.p =this.p.add(circle2.p);
circle2.r =this.r + circle2.r ;
return circle2;
}
@Override
public String toString() {
return String.format("圆心:(%f,%f) 半径:%f",p.x,p.y,r);
}
}
package _05_第五章泛型.E202_05_02_数据相加;
public class Complex implements Add<Complex> {
private int real;//实部
private int imag;//虚部
public Complex(int real, int imag){
this.real = real;
this.imag = imag;
}
public Complex add(Complex complex2){
complex2.real = this.real + complex2.real;
complex2.imag = this.imag + complex2.imag;
return complex2;
}
public void Print(Complex complex){
System.out.printf("复数和 = %d + %d i \n",complex.real,complex.imag);
System.out.printf("复数差 = %d + (%d) i",complex.real,complex.imag);
}
}
package _05_第五章泛型.E202_05_02_数据相加;
public class Point implements Add<Point> {
public float x;//x是属性
public float y;
public Point(float x,float y){ //x是形参 函数内部有效
this.x = x; //如果写成 x = x就错了 ,需要加this 不然起不到改float x的作用
this.y = y;
}
public Point add(Point point2){
point2.x = (point2.x + this.x)/2f;
point2.y = (point2.y + this.y)/2f;
return point2;
}
@Override
public String toString() {
return String.format("(%f,%f)",x,y);
}
}