Answer to Question #274255 in Java | JSP | JSF for besie

Question #274255

Using Overloading Constructor


Write a class named ‘Rectangle’ with 2 instance variables:

 Variables: length and width (both type double)

 Also create a method that will compute the area of a rectangle

 The class should have 3 constructors:

i. No parameter – values of both length and width are assigned zero

ii. 1 parameter – both the length and width will be assigned with same number

iii. 2 parameters – 2 numbers are assigned as length and width respectively


Also create a class with Main Method, where you will:

 Create 3 objects of the class Rectangle:

 one with no parameters

 one with 1 parameter

 another one with 2 parameters

 Allow the user to enter the value for the objects that requires parameter(s)

 Print the area of the Rectangle for each object.


1
Expert's answer
2021-12-02T00:35:16-0500
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner s = new Scanner(System.in);

    Rectangle rect0 = new Rectangle();     

    System.out.println("Enter a value for second rect (var0): ");
    double val0 = s.nextDouble();
    Rectangle rect1 = new Rectangle(val0);

    System.out.println("Enter names fir third rest (var1, var2): ");
    double var1 = s.nextDouble(), var2 = s.nextDouble();
    Rectangle rect2 = new Rectangle(var1, var2);

    System.out.println("Area of rect0: " + rect0.getArea());
    System.out.println("Area of rect1: " + rect1.getArea());
    System.out.println("Area of rect2: " + rect2.getArea());
  }
}
class Rectangle {
  private double length;
  private double width;

  Rectangle() {
    this.length = 0;
    this.width = 0;
  }
  Rectangle(double val0) {
    this.length = val0;
    this.width = val0;
  }
  Rectangle(double val1, double val2) {
    this.length = val1;
    this.width = val2;
  }

  double getArea() { return this.length * this.width; }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS