java 类的继承(转)

这个星期主要是学习了Java中类的继承问题.继承就是由已有的类创建新类,通过子类继承父类的方法,实现一些功能.
下面就是老师布置作业的其中一个:
定义父类圆,通过继承,获得子类球、圆锥、圆柱,子类具有计算体积的功能。
1)新建文件夹Test1;
2)定义父类Circle,Circle具有保护成员变量半径r,并提供成员方法setR、getArea和带参数的构造函数;
3)子类球Ball具有获得体积的成员方法getValume;
4)子类圆锥Cone、圆柱Cylinder具有私有的成员变量高high、设置高的成员方法setHigh()和获得体积的getValume;
5)3个子类都提供带参数的构造函数;
6)3个子类在重设半径后,应获得正确的体积;
7)编写测试类进行测试

代码:
Circle.java
package test3;

public class Circle {

public static void main(String[] args) {
// TODO Auto-generated method stub

}
protected double r;

public void setR(double r) {
this.r = r;
}
public double getArea() {
return 3.14*r*r;
}
// public Circle(double r) {
// super();
// this.r = r;
// }
public Circle() {
super();
// TODO Auto-generated constructor stub
}


}

Ball.java
package test3;
import java.util.Scanner;
public class Ball extends Circle{

public static void main(String[] args) {
// TODO Auto-generated method stub
reader = new Scanner(System.in);
Ball ball =new Ball();
double r;
System.out.println("请输入圆的半径:");
r = reader.nextDouble();
ball.setR(r);
System.out.println("体积:" + ball.getValumn());

}
private static Scanner reader;
public double getValumn() {
return getArea()*r*4/3;
}
public Ball() {
super();
// TODO Auto-generated constructor stub
}


}

Cone.java
package test3;
import java.util.Scanner;
public class Cone extends Circle{

// public Cone(double r) {
// super(r);
// // TODO Auto-generated constructor stub
// }
//private double valumn;
private double high;
private static Scanner reader;

public void setHigh(double high) {
this.high = high;
}

public double getValumn() {
return getArea() *high/3;
}

public Cone() {
super();
// TODO Auto-generated constructor stub
}

public static void main(String[] args) {
// TODO Auto-generated method stub
reader = new Scanner(System.in);
Cone cone = new Cone();
double high,r;
System.out.println("请输入圆锥的高:");
high = reader.nextDouble();
System.out.println("请输入圆锥的半径:");
r = reader.nextDouble();
cone.setHigh(high);
cone.setR(r);
System.out.println("体积:" + cone.getValumn());

}

}

Cylinder.java
package test3;
import java.util.Scanner;

public class Cylinder extends Circle{

public static void main(String[] args) {
// TODO Auto-generated method stub
reader = new Scanner(System.in);
Cylinder cy = new Cylinder();
double r,high;
System.out.println("请输入的高:");
high = reader.nextDouble();
System.out.println("请输入半径:");
r = reader.nextDouble();
cy.setHigh(high);
cy.setR(r);
System.out.println("体积:" + cy.getValumn());
}
private double high;
private static Scanner reader;

public void setHigh(double high) {
this.high = high;
}

public double getValumn() {
return getArea() *high;
}

public Cylinder() {
super();
// TODO Auto-generated constructor stub
}

}

Java中类的继承,更多的可以查看http://www.cnblogs.com/dolphin0520/p/3803432.html,这里有详细的介绍,我大致就是看这个学习的.
---------------------
作者:yang_tang
来源:CSDN
原文:https://blog.csdn.net/yang_tang/article/details/78070791?utm_source=copy
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2018-10-17 08:37  代码缔造的帝国  阅读(1545)  评论(0编辑  收藏  举报