Advertisement
fosterbl

Square.java COMPLETE

Feb 6th, 2020
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. class Rectangle{
  2.    private int length;
  3.    private int width;
  4.  
  5.    public Rectangle(){
  6.       length = 1;
  7.       width = 1;
  8.    }
  9.  
  10.    public Rectangle(int l, int w){
  11.       length = l;
  12.       width = w;
  13.    }
  14.  
  15.    public void draw(){
  16.       for(int i=0; i < length; i++)
  17.       {
  18.          for(int j=0; j < width; j++)
  19.             System.out.print("* ");
  20.          System.out.println();
  21.       }
  22.       System.out.println();
  23.    }
  24.  
  25.    //5.Add an area() method to Rectangle that computes the area of the rectangle. Does it work for squares too? Test it.
  26.    public int area(){
  27.       return length * width;
  28.    }
  29. }
  30.  
  31. //6.Add another subclass called LongRectangle which inherits from Rectangle but has the additional condition that the length is always 2 x the width. Write constructors for it and test it out.
  32. class LongRectangle extends Rectangle{
  33.    public LongRectangle(){
  34.       super(2,1);
  35.    }
  36.    public LongRectangle(int w){
  37.       super(w*2, w);
  38.    }
  39. }
  40.  
  41. // 1. Make the class square inherit from Rectangle
  42. public class Square extends Rectangle{
  43.    // 2. Add a Square no-argument constructor
  44.    public Square(){
  45.       super();
  46.    }
  47.    // 3. Add a Square constructor with 1 argument for a side
  48.    public Square(int side){
  49.       super(side, side);
  50.    }
  51.    
  52.    public static void main(String[] args){
  53.       Rectangle r = new Rectangle(3,5);
  54.       r.draw();
  55.       // 4. Uncomment these to test
  56.       Square s1 = new Square();
  57.       s1.draw();
  58.       Square s = new Square(3);
  59.       s.draw();
  60.    }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement