JAVA you will design and write a class that represents a real-world object of yo
ID: 649584 • Letter: J
Question
JAVA
you will design and write a class that represents a real-world object of your choice. In the second part, you will write a program that demonstrates the use of the class.
Part I:
Select a "real-world" object that has not been used in class lecture and/or the textbook.
The object you choose must be defined by at least:
Have at least two characteristics (attributes).
Have at least two behaviors (operations).
The class that you write to represent the object must minimally meet the requirements of:
The "data" part must declare the attributes correctly.
The "operations" part must include at least the following methods:
A no-arg constructor method that creates an object with reasonable defaults for the initial state.
The set and get methods for each attribute.
Two methods that appropriately carry out the behaviors identified in the design.
Bonus (10 points) : A constructor that takes the initial values for the object's attributes from the user rather than setting defaults.
Part II: Write a "client" class that demonstrates the use of the object. Examples from class: RectangleDemo class & CircleDemo.
Explanation / Answer
package demo;
import java.util.Scanner;
class Shape {
private int length;
private int bredth;
public Shape(int length,int bredth)
{
this.bredth=bredth;
this.length=length;
}
public int getArea()
{
return length*bredth;
}
public int getPerimeter()
{
return 2*(length+bredth);
}
}
class RectangleDemo extends Shape
{
private int length;
private int bredth;
public int getArea()
{
return length+bredth;
}
public int getPerimeter()
{
return 2*(length+bredth);
}
public RectangleDemo(int length, int bredth) {
super(length, bredth);
this.bredth=bredth;
this.length=length;
}
}
class CircleDemo extends Shape
{
private int length;
private int bredth;
public int getArea()
{
return length*bredth;
}
public int getPerimeter()
{
return 2*(length+bredth)/2;
}
public CircleDemo(int length, int bredth) {
super(length, bredth);
this.bredth=bredth;
this.length=length;
}
}
public class DemoClasses{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("enter the length");
int len=scan.nextInt();
System.out.println("enter the bredth");
int bred=scan.nextInt();
Shape rect=new RectangleDemo(len, bred);
Shape cir=new CircleDemo(len, bred);
System.out.println("area of rectangle "+rect.getArea());
System.out.println("perimeter of rectangle "+rect.getPerimeter());
System.out.println("area of circle "+cir.getArea());
System.out.println("perimeter of circle "+cir.getPerimeter());
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.