/**
* AI: Francisco Lara-Dammer
* Lab 9
* Write two classes: Cube and Sphere with methods getArea, and getVolume.
* Because these methods are common to both classes, it is a good idea
* to write a third abstract class Solid. Test your code to calculate
* the areas and volumes of a cube and sphere with parameters of your choice.
*/
public abstract class Solid{
double itsParameter;
abstract double getArea();
abstract double getVolume();
public static void main(String args[]){
//Testing for a cube of side x, and for a sphere of radius 10.
Solid s1 = new Cube(10.0);
Solid s2 = new Sphere(10.0);
System.out.println("Area of a cube of side 10 = " + s1.getArea());
System.out.println("Volume of a cube of side 10 = " + s1.getVolume());
System.out.println("Area of a sphere of side 10 = " + s2.getArea());
System.out.println("Volume of a sphere of side 10 = " + s2.getVolume());
}
}
class Cube extends Solid{
/**
* Constructs a Cube. this.itsParameter is inherited from Solid
*/
Cube(double itsParameter){
this.itsParameter = itsParameter;
}
/**
* Area of the cube = 6*x^2, where x is the length of its side.
*/
double getArea(){
return 6*this.itsParameter*this.itsParameter;
}
/**
* Volume of the cube = x^3.
*/
double getVolume(){
return this.itsParameter*this.itsParameter*this.itsParameter;
}
}
class Sphere extends Solid{
static final double pi = Math.PI;
/**
* Constructs a Sphere. this.itsParameter is inherited from Solid
*/
Sphere(double itsParameter){
this.itsParameter = itsParameter;
}
/**
* Area of the sphere = 4*pi*radius^2
*/
double getArea(){
return 4*pi*itsParameter*itsParameter;
}
/**
* Volume of the sphere = 4/3*pi*radius^3
*/
double getVolume(){
return 4/3.0*pi*itsParameter*itsParameter*itsParameter;
}
}