This assignment has 4 sub-sections.
Use the JOptionPane class for all required input/output.
a) Write a superclass called Shape (as shown in the class diagram), which contains:
· Two instance variables color (String) and filled (boolean).
· Two constructors: a no-arg (no-argument) constructor that initializes the color to "green" and filled to true, and a constructor that initializes the color and filled to the given values.
· Getter and setter for all the instance variables. By convention, the getter for a boolean variable xxx is called isXXX() (instead of getXxx() for all the other types).
· A toString() method that returns "A Shape with color of xxx and filled/Not filled".
Write a test program to test all the methods defined in Shape.
import java.util.*;
import javax.swing.JOptionPane;
class Shape {
private String color;
private boolean filled;
public Shape() {
this.color = "green";
this.filled = true;
}
public Shape(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public String toString() {
String filledStr = "filled";
if (!filled) {
filledStr = "Not filled";
}
return "A Shape with color of " + color + " and " + filledStr;
}
/**
* @return the color
*/
public String getColor() {
return color;
}
/**
* @param color the color to set
*/
public void setColor(String color) {
this.color = color;
}
/**
* @return the filled
*/
public boolean isFilled() {
return filled;
}
/**
* @param filled the filled to set
*/
public void setFilled(boolean filled) {
this.filled = filled;
}
}
class App {
public static void main(String[] args) {
Shape shape = new Shape();
String color = JOptionPane.showInputDialog("Enter color");
shape.setColor(color);
int filledInt = Integer.parseInt(JOptionPane.showInputDialog("Enter 1. Is filled, 2. Is NOT filled: "));
shape.setFilled(false);
if (filledInt == 1) {
shape.setFilled(true);
}
JOptionPane.showMessageDialog(null, shape.toString());
color = JOptionPane.showInputDialog("Enter color");
filledInt = Integer.parseInt(JOptionPane.showInputDialog("Enter 1. Is filled, 2. Is NOT filled: "));
boolean isFilled = false;
if (filledInt == 1) {
isFilled = true;
}
shape = new Shape(color, isFilled);
String filledStr = "filled";
if (!shape.isFilled()) {
filledStr = "Not filled";
}
JOptionPane.showMessageDialog(null, "A Shape with color of " + shape.getColor() + " and " + filledStr);
}
}
Comments
Leave a comment