Java杂谈之接口和继承的经典案例

以下是关于接口和的一个经典案例。

包含Shape接口(形状),Point类(点),Circle类(圆),Column类(圆柱),Test类(测试)


一些注意点和知识在其中的注释中已经说明了,就不额外赘述了。

1.Shape接口:

package JavaInterface;

public interface Shape {
	public abstract double area();

	public abstract double volume();

	public abstract String getName();
}

2.Point类:

package JavaInterface;

public class Point implements Shape {
	private int x;
	private int y;

	public Point() {
		this.x = 0;
		this.y = 0;
	}

	public Point(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;
	}

	@Override
	public double area() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public double volume() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "点:[" + this.x + "," + this.y + "]";
	}

}

3.Circle类:

package JavaInterface;

public class Circle extends Point implements Shape {
	private int r;

	public Circle() {
		this.r = 0;
	}

	public Circle(int x, int y, int r) {
		super(x, y);
		this.r = r;
	}
	
	@Override
	public double area() {
		return Math.PI * r*r;
	}
	
	@Override
	public String getName() {
		return "圆:半径=" + this.r;
	}

	public int getR() {
		return r;
	}

	public void setR(int r) {
		this.r = r;
	}
	

}

4.Column类:

package JavaInterface;

public class Column extends Circle {
	private int h;

	public Column() {
		this.h = 0;
	}

	public Column(int x, int y, int r, int h) {
		super(x, y, r);
		this.h = h;
	}

	@Override
	public String getName() {
		return "圆柱:高度=" + this.h;
	}

	@Override
	public double area() {
		return super.area() * 2 + 2 * Math.PI * h * super.getR();
	}

	@Override
	public double volume() {
		return super.area() * h;
	}
}

5.Test类:

package JavaInterface;

public class Test {
	public static void main(String[] args) {
		//圆
		//将对象的引用定义为接口,即面向接口的编程
		Shape sc = new Circle(2,4,8);
		Circle c = new Circle(2,4,8);
		System.out.println("类型:"+c.getName());
		System.out.println("面积:"+c.area());
		System.out.println("体积:"+c.volume());
		//圆柱
		Column col = new Column(2,4,8,2);
		System.out.println("类型:"+col.getName());
		System.out.println("面积:"+col.area());
		System.out.println("体积:"+col.volume());
	}

}

6.结果截图:

Java杂谈之接口和继承的经典案例_第1张图片


你可能感兴趣的:(Java)