Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Rectangle{
- private int length;
- private int width;
- public Rectangle(){
- length = 1;
- width = 1;
- }
- public Rectangle(int l, int w){
- length = l;
- width = w;
- }
- public void draw(){
- for(int i=0; i < length; i++)
- {
- for(int j=0; j < width; j++)
- System.out.print("* ");
- System.out.println();
- }
- System.out.println();
- }
- //5.Add an area() method to Rectangle that computes the area of the rectangle. Does it work for squares too? Test it.
- public int area(){
- return length * width;
- }
- }
- //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.
- class LongRectangle extends Rectangle{
- public LongRectangle(){
- super(2,1);
- }
- public LongRectangle(int w){
- super(w*2, w);
- }
- }
- // 1. Make the class square inherit from Rectangle
- public class Square extends Rectangle{
- // 2. Add a Square no-argument constructor
- public Square(){
- super();
- }
- // 3. Add a Square constructor with 1 argument for a side
- public Square(int side){
- super(side, side);
- }
- public static void main(String[] args){
- Rectangle r = new Rectangle(3,5);
- r.draw();
- // 4. Uncomment these to test
- Square s1 = new Square();
- s1.draw();
- Square s = new Square(3);
- s.draw();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement