JAVA学习日记28-0802

今天学了什么

以点类和圆类设计圆柱类

点类:

package cylinder;

public class Point {

protected double x,y;
Point(double x,double y){
this.x=x;
this.y=y;
}
public void setx(double x) {
this.x=x;
}
public void sety(double y) {
this.y=y;
}
public double getx() {
return x;
}
public double gety() {
return y;
}

}

圆类:

package cylinder;

public class Circle extends Point {
final double PI=3.14;
protected double radius;
public Circle(double x,double y,double radius) {
super(x,y);
this.radius=radius;
}
public void setr(double r) {
this.radius=r;
}
public double getr() {
return radius;
}
public double area() {
return PI*radius*radius;
}
}

圆柱类:

package cylinder;

public class Cylinder extends Circle {
private double h;
public Cylinder(double x, double y, double radius, double h) {
super(x, y, radius);
this.h=h;
}
public void seth(double h) {
this.h=h;
}
public double geth() {
return h;
}
public double sarea() {
return 2*area()+2*PI*radius*h;
}
public double volume() {
return area()*h;
}

public static void main(String[] args) {
Cylinder c = new Cylinder(0,0,0,0);
c.setx(1);
c.sety(1);
c.setr(2);
c.seth(3);
System.out.println("x="+c.getx()+" y="+c.gety()+" radius="+c.getr()+" area="+c.area());
System.out.println("h="+c.geth()+" sarea="+c.sarea()+" volume="+c.volume());
}
}

运行截图:

遇到的问题

数据无法继承,会在子类中为默认的0,解决方法:用super()方法,在main()方法中,只对圆柱类进行实例化。

明天计划

找题目练习

原文地址:https://www.cnblogs.com/a8047/p/13419426.html