Hey, I have a lab to do, but I'm stuck on one part of it which is probably really easy but I can't figure it out. This is what I have so far, but it doesn't compile, and then I have to use polymorphism to output it. The purpose of this method is to truly demonstrate polymorphism since one output method will be capable of displaying both the shape and the number of sides of ANY class that implements Shape.
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
public class Lab21a {
@SuppressWarnings("deprecation")
public static void main(String args[]) {
Windows win = new Windows();
win.setSize(800, 600);
win.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
win.show();
}
}
@SuppressWarnings("serial")
class Windows extends Frame {
public void paint(Graphics g) {
drawGrid(g);
Square shape1 = new Square(g);
Triangle shape2 = new Triangle(g);
Octagon shape3 = new Octagon(g);
Circle shape4 = new Circle(g);
output(g, shape1);
output(g, shape2);
output(g, shape3);
output(g, shape4);
}
public void drawGrid(Graphics g) {
g.drawLine(0, 300, 800, 300);
g.drawLine(400, 0, 400, 600);
g.drawString("Square", 20, 50);
g.drawString("Triangle", 420, 50);
g.drawString("Octagon", 20, 320);
g.drawString("Circle", 420, 320);
}
}
abstract interface Shape {
public final double PI = Math.PI;
public abstract void drawShape(Graphics g);
public abstract void displayNumSides(Graphics g);
}
abstract class Shape2 implements Shape{
private int numSides;
private String shapeName;
private Graphics g;
private int messageX, messageY;
public void displayNumSides(Graphics g) {
g.drawString("A " + shapeName + " has " + numSides + " sides.",
messageX, messageY);
}
class Square{
public Square(Graphics g1) {
numSides = 4;
shapeName = "Square";
g = g1;
messageX = 100;
messageY = 250;
}
public void drawShape(Graphics g) {
g.fillRect(100, 50, 150, 150);
}
}
class Triangle {
public Triangle(Graphics g1) {
numSides = 3;
shapeName = "Triangle";
g = g1;
messageX = 500;
messageY = 250;
}
public void drawShape(Graphics g) {
Polygon poly = new Polygon();
poly.addPoint(600, 50);
poly.addPoint(700, 200);
poly.addPoint(500, 200);
g.fillPolygon(poly);
}
}
class Octagon {
public Octagon(Graphics g1) {
numSides = 8;
shapeName = "Octagon";
g = g1;
messageX = 100;
messageY = 550;
}
public void drawShape(Graphics g) {
Polygon poly = new Polygon();
poly.addPoint(100, 400);
poly.addPoint(150, 350);
poly.addPoint(200, 350);
poly.addPoint(250, 400);
poly.addPoint(250, 450);
poly.addPoint(200, 500);
poly.addPoint(150, 500);
poly.addPoint(100, 450);
g.fillPolygon(poly);
}
}
class Circle {
public Circle(Graphics g1) {
numSides = 0;
shapeName = "Circle";
g = g1;
messageX = 500;
messageY = 550;
}
public void drawShape(Graphics g) {
g.fillOval(500, 350, 150, 150);
}
}
}