Computer Science
Design a class 'Rectangle' with the following specifications:
class Rectangle
Data members/Instance variables
int length, breadth, area, perimeter
Member methods:
void input( ) : to accept length and breadth of a rectangle.
void calculate( ) : to calculate area and perimeter of rectangle.
void display( ) : to print area and perimeter of rectangle.
Write a main method to create an object of class 'Rectangle' and call the member methods.
Objects & Classes
49 Likes
Answer
import java.util.Scanner;
class Rectangle {
int length;
int breadth;
int area;
int perimeter;
void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter length of rectangle: ");
length = in.nextInt();
System.out.print("Enter breadth of rectangle: ");
breadth = in.nextInt();
}
void calculate() {
area = length * breadth;
perimeter = 2 * (length + breadth);
}
void display() {
System.out.println("Area of Rectangle = " + area);
System.out.println("Perimeter of Rectangle = " + perimeter);
}
public static void main(String args[]) {
Rectangle obj = new Rectangle();
obj.input();
obj.calculate();
obj.display();
}
}
Answered By
33 Likes
Related Questions
In what way is a class helpful in creating a user defined data type?
What do you mean by instantiating a class?
Design a class 'Time' with the following specifications:
class Time
Data members/Instance variables
int hour, min, secMember Methods:
void gettime( ) : to accept a time in hour, minute and second. void showtime( ) : to display the time in terms of hour, minute and second.Write a main method to create an object of class 'Time' and call the member methods.
Write a class template 'Calculator' with the following specifications:
class Calculator
Data members/Instance variables
int a,b,cMember Methods:
void readdata( ) : to accept the values of a and b.
void add( ) : to add a and b and place the result in c.
void sub( ) : to subtract b from a and place the result in c. Display the result.
void mul( ) : to multiply a and b and place the result in c. Display the result.
void div( ) : to divide a by b and place the result in c. Display the result.Write a main method to create an object of class 'Calculator' and call the member methods to enable the task.