//Shape3D.java //demo of inheritance and polymorphism import java.awt.*; // public abstract class Shape3D { private Point3D center; private Color color; private String id; public Shape3D() { center = new Point3D(); center.x = (int)(Math.random()*400); center.y = center.z = (int)(Math.random()*400); // color = new Color( Color.WHITE ); color = Color.WHITE; } public Shape3D( Point3D p, Color c ) { center = p; //fix color = c; //fix } public Point3D getCenter() { return center; } public void setID( String newID ) { id = newID; } public String getID() { return id; } public int getX() { return center.x; } public int getY() { return center.y; } public int getZ() { return center.z; } public void setColor( Color newColor ) { color = newColor; } public Color getColor() { return color; } public void move( int dx, int dy, int dz ) { center.x += dx; center.y += dy; center.z += dz; } public void moveTo( Point3D newCenter ) { center.x = newCenter.x; center.y = newCenter.y; center.z = newCenter.z; } //abstract methods must be implmented in every (non-abstract) subclass public abstract double getArea(); public abstract double getVolume(); public abstract void draw( Graphics g ); } class Point3D extends Point { public int z; public Point3D() { super(0,0); z = 0; } public Point3D( Point3D p ) { super( p.x, p.y ); z = p.y; } } class Cone extends Shape3D { private double radius; private double height; public Cone() { radius = 1; height = 1; setID( "cone " + (int)(Math.random()*1000) ); } public Cone( double r, double h ) { radius = r; height = h; } //others... public double getArea() { return Math.PI * radius * Math.sqrt(radius * radius + height * height) + Math.PI * radius * radius; } public double getVolume() { return 1.0/3.0 * Math.PI * radius * radius * height; } public void draw( Graphics g ){ g.drawString( getID(), getX(), getY()); } } class Sphere extends Shape3D { private double radius; public Sphere() { radius = 1; setID( "sphere " + (int)(Math.random()*1000) ); } public Sphere( double r ) { radius = r; } //others... public double getArea() { return 4 * Math.PI * radius * radius; } public double getVolume() { return 4.0/3.0 * Math.PI * radius * radius * radius; } public void draw( Graphics g ){ g.drawString( getID(), getX(), getY()); } } /* //calculate the area of a cylinder cylarea = 2 * PI * radius * height + 2 * PI * radius * radius; //calculate the area of a sphere spharea = //calculate the area of a cone //calculate the area of a cube cubarea = 6 * height * height; //calculate the volume of sphere sphvol = //calculate the volume of a cylinder cylvol = PI * radius * radius * height; //calculate the volume of a cone //calculate the volume of cube cubvol = height * height * height; */