Implement a subclass Square that extends the Rectangle class

//Implement a subclass Square that extends the Rectangle class. In the constructor, accept the x- and y-positions of the center and the side length of the square. Call the setLocation and setSize methods of the Rectangle class. Look up these methods in the documentation for the Rectangle class. Also supply a method getArea that computes and returns the area of the square. Write a sample program that asks for the center and side length, then prints out the square (using the toString method that you inherit from Rectangle) and the area of the square.

//Ok... So this is last minute, but I don't understand what is wrong with my code it is giving me the error that square cannot be resolved to a type... So here is my Class:

    import java.awt.Rectangle;


 public class Squares22 extends Rectangle 
{


public Squares22(int x, int y, int length) {
    setLocation(x - length / 2, y - length / 2);
    setSize(length, length);
}

public int getArea() {
    return (int) (getWidth() * getHeight());
}

public String toString() {
    int x = (int) getX();
    int y = (int) getY();
    int w = (int) getWidth();
    int h = (int) getHeight();
    return "Square[x=" + x + ",y=" + y + ",width=" + w + ",height=" + h
           + "]";
}
}

//And this is my tester class...

import java.util.Scanner;

public class Squares22Tester

  {
   public static void main(String[] args) 
  {

Scanner newScanx =  new Scanner(System.in);
Scanner newScany =  new Scanner(System.in);
Scanner newScanl =  new Scanner(System.in);


System.out.println("Enter x:");
String x2 = newScanx.nextLine();
System.out.println("Enter y:");
String y2 = newScany.nextLine();
System.out.println("Enter length:");
String l2 = newScanl.nextLine();

int x = Integer.parseInt(x2);
int y = Integer.parseInt(y2);
int length = Integer.parseInt(l2);

  Square sq = new Square(x, y, length); 
  System.out.println(sq.toString()); 

  }
}

//Can anyone please help my assignment is due at midnight.. It says square cannot be resolved to a type on the tester class when compliling....


Square isn't the name of your class. The name of the class is 'Squares22'. This is why 'Square' cannot be recognized. Change Square in the test to Squares22 or vice versa. This should solve your issues.

链接地址: http://www.djcxy.com/p/83250.html

上一篇: java中Square方法的继承

下一篇: 实现扩展Rectangle类的子类Square