java-类和对象练习

  1. (1)设计一个表示二维平面上点的类Point,包含有表示坐标位置的protected类型的,成员变量x和y,获取和设置x和y值的public方法。
    (2)设计一个表示二维平面上圆的类Circle,它继承自类Point,还包含有表示圆半径的protected类型的成员变量r、获取和设置r值的public方法、计r的public方法。
    (3)设计一个表示圆柱体的类Cylinder,它继承自类Circle,还包含有表示圆柱体高的protected类型的成员变量h、获取和设置h值的public方法、计算圆柱体体积的public方法。
    (4)建立Cylinder对象,输出其轴心位置坐标、半径、面积、高及其体积的值。
    Point类
public class Point {
	protected double x;
	protected double y;
	
	
	public Point(double x,double y) {
		this.x = x;
		this.y = y;
	}
	
	public double getX() {
		return x;
	}

	public void setX(double x) {
		this.x = x;
	}

	public double getY() {
		return y;
	}

	public void setY(double y) {
		this.y = y;
	}

	

}

Circle类

public class Circle extends Point {
	protected double r;
	
	public Circle(double x, double y,double r) {
		super(x, y);
		this.r = r;
	}
	
	public double getR() {
		return r;
	}

	public void setR(double r) {
		this.r = r;
	}
	public double area(){
		return Math.PI*this.r*this.r;
		
	}

}

Cylinder类

public class Cylinder extends Circle{
	protected double h;
	
	
	public Cylinder(double x, double y, double r,double h) {
		super(x, y, r);
		this.h = h;
	}

	public double capacity(){
		return super.area()*this.h;
	}
	public double area(){
		return Math.PI*this.r*this.r*2+2*Math.PI*this.r*h;
		
	}
	public double getH() {
		return h;
	}

	public void setH(double h) {
		this.h = h;
	}

}

TestClass类

public class TestClass {

	public static void main(String[] args) {
		double x = 12;
		double y = 10;
		double r = 5;
		double h = 9;
		
		Cylinder c = new Cylinder(x,y,r,h);
		
		System.out.println("轴心坐标为: "+"("+c.getX()+","+c.y+")");
		System.out.println("半径为: "+c.getR());
		System.out.println("高为: "+c.getH());
		System.out.println("面积为: "+c.area());
		System.out.println("体积为: "+c.capacity());
	}

}

你可能感兴趣的:(Java基础语法,java,类和对象,多态,继承)