定义抽象类形状。形状包含专用字符串颜色。形状包含抽象方法:Shape(), public Shape(String s) 、public double getArea() 、double getVolume()、ToString()、定义圆从形状继承。圆包含私有数据双 x,y 作为中心位置,双半径。圆圈覆盖形状中的所有抽象方法。定义圆锥体从圆圈继承。锥包含双高的私人数据。锥体从圆继承的方法。
package experience6;
import java.util.*;
public class experience6____shapeabstract {
public static void printfo (Object o) {
if(o instanceof Circle) {
System.out.println(((Circle)o).toString());
}
else if(o instanceof Cone) {
System.out.println(((Cone)o).toString());
}
else System.out.println("can not know what the shape is");
}
public static void main(String[] args) {
Object c1=new Circle(1,1,1);
Object c2=new Cone(1);
printfo(c1);
printfo(c2);
}
}
abstract class Shape{
private String color;
public Shape() {
color="whilte";
}
public Shape(String s) {
color=s;
}//构造方法不能抽象
public String getcolor() {
return color;
}
public abstract double getarea();
public abstract double getvolume();
public String toString() {
return "the color is"+color;
}
}
class Circle extends Shape{
private double x;
private double y;
private double radious;
public Circle(){
this(1,1,1);
}
public Circle(double x,double y,double radious) {
this.x=x;
this.y=y;
this.radious=radious;
}
public double getarea() {
return 3.14*radious*radious;
}
public double getvolume() {
return 0;
}
public double getradious() {
return radious;
}
public String toString() {
return " the color is "+this.getradious()+" the area is "+this.getarea()+" the volumen is "+this.getvolume();
}
}
class Cone extends Circle{
private Date createddated;
private double height;
public Cone(double height){
this.height=height;
createddated=new Date();
}//无论子类构造方法有参无参,只要没有显示调用父类的构造方法,那么在子类构造方法第一句一定会加上父类的无参构造
public double getarea() {
return 3.14*this.getradious()*this.getradious();
}
public double getvolume() {
return height*3.14*this.getradious();
}
public String toString() {
return " the color is "+this.getcolor()+" the cone heigh is "+this.height+" the area is "+this.getarea()+" the volume is "+this.getvolume();
}
}