Define a class named Sphere that inherits the properties of the class Circle in Question 1. The class also contains:
â?¢ A private data field named weight of type double with the default value 1.0. â?¢ A default Sphere constructor. â?¢ A constructor that initializes the Sphere objectâ??s radius and weight through the constructor arguments. â?¢ A public method to display the Sphere objectâ??s data. â?¢ A public method named getSurfaceArea() that calculates and returns the surface area of the Sphere object. â?¢ A public method named getVolume() that calculates and returns the Sphere objectâ??s volume.
Write another class to test Circle and Sphere class. The class will create a Circle object and a Sphere object based on the given input from the user. Use the proper JOptionPane method to get the input from the user. Display the properties of both created objects. Display surface area and circumference of the Circle object and the surface are and volume of the Sphere object.
Hi Friend,
Try the following code:
import javax.swing.*;
class Circle{
protected double radius=1;
String color="red";
private static double pi=3.142;
Circle(){}
Circle(double radius){
this.radius=radius;
}
public void display(){
System.out.println("Radius:"+radius+"\nColor:"+color);
}
public void changeColor(String col) {
color = col;
}
public double getSurfaceArea(){
double area=pi*radius*radius;
return area;
}
public double getCircumference(){
double circumference=2*pi*radius;
return circumference;
}
}
class Sphere extends Circle{
private double weight=1;
private static double pi=3.142;
Sphere(){}
Sphere(double r,double weight){
super.radius = r;
this.weight=weight;
}
public void changeColor(String col) {
super.color = col;
}
public void display(){
System.out.println("Radius:"+super.radius+"\nWeight:"+weight+"\nColor:"+super.color);
}
public double getSurfaceArea(){
double radius=super.radius;
double area=4*pi*radius*radius*radius;
return area/3;
}
public double getVolume(){
double vol=4*pi*radius*radius;
return vol;
}
}
public class TestBoth
{
public static void main(String[]args){
String st1=JOptionPane.showInputDialog(null,"Enter radius");
double r1=Double.parseDouble(st1);
Circle c=new Circle(r1);
c.changeColor("Pink");
c.display();
double saOFCircle=c.getSurfaceArea();
System.out.println("Surface Area Of Circle: "+saOFCircle);
double cf=c.getCircumference();
System.out.println("Circumference: "+cf);
System.out.println();
String st2=JOptionPane.showInputDialog(null,"Enter radius");
double r2=Double.parseDouble(st2);
Sphere s=new Sphere(r2,5);
c.changeColor("Blue");
s.display();
double saOFSphere=s.getSurfaceArea();
System.out.println("Surface Area Of Sphere: "+saOFSphere);
double voloume=s.getCircumference();
System.out.println("Volume: "+voloume);
}
}
Thanks