How to assign an object property value to a variable in Java? - java

The following code is what I'm having issues understanding:
public class Rectangle {
public Rectangle() {
double width = 1;
double height = 1;
}
public Rectangle(double w, double h) {
double width = w;
double height = h;
}
public double getArea(double w, double h) {
return (w*h);
}
public double getPerimeter(double w, double h) {
return ((2*w)+(2*h));
}
public static void main(String[] args) {
Rectangle oldRectangle = new Rectangle(4, 40);
Rectangle newRectangle = new Rectangle(3.5, 35.9);
double height1 = oldRectangle.height;
double height2 = newRectangle.height;
double width1 = oldRectangle.width;
double width2 = newRectangle.width;
System.out.println("Width of Rectangle 1 is: " + 4);
System.out.println("Height of Rectangle 1 is: " + 40);
System.out.println("Area of Rectangle 1 is: " + oldRectangle.getArea(4, 40));
System.out.println("Perimeter of Rectangle 1 is: " + oldRectangle.getPerimeter(4, 40));
System.out.println("Width of Rectangle 1 is: " + 3.5);
System.out.println("Height of Rectangle 1 is: " + 35.9);
System.out.println("Area of Rectangle 1 is: " + newRectangle.getArea(3.5, 35.9));
System.out.println("Perimeter of Rectangle 1 is: " + newRectangle.getPerimeter(3.5, 35.9));
}
}
I was instructed to create two constructors for a Rectangle class—one with no arguments but assigned a default value of 1 for both variables width and height. The second constructor was to contain parameters that would take in two doubles that would get assigned to their appropriate variable.
I was then told to create two 'get()' methods that returned their respective values—in my case, they were perimeter and area of said Rectangle.
I was then instructed to create two Rectangle instances, one with a width of 4 and a height of 40—and another with a width of 4.5 and a height of 35.9. So, I did just that and made two new Rectangle objects, as you can see.
Lastly, I was instructed to print out the Width, Height, Perimeter, and Area of both Rectangle objects. My issue is that I don't know of a way to reference them. I took a beginners tutorial class for JavaScript and if I'm not mistaken, I recall there was a way to reference a property value of an object by assigning it to a variable. Again, I'm saying "If I'm not mistaken", so I could be wrong. It's been a while...
I do realize that Java and Java Script are entirely different things in their own right. Java Script was a scripting language developed and based off of Java.
Anyway, any help will be grand.
Please feel free to help me understand how I can implement what I'm trying to do by giving examples. You don't have use my exact code, but I'd like to be able to get my code to make more sense.. I'm using Eclipse btw.

You are on the right track. What you are looking to do is something like this:
public double getArea(Rectangle r){
return r.width*r.height;
}
public double getPerimeter(Rectangle r){
return (2*r.width + 2*r.height);
}
For the print statements you are hard-coding in values which you dont have to do.
System.out.println("Width of Rectangle 1 is: " + oldRectangle.width);
System.out.println("Height of Rectangle 1 is: " + oldRectangle.height);
System.out.println("Area of Rectangle 1 is: " + getArea(oldRectangle));
System.out.println("Perimeter of Rectangle 1 is: " + getPerimeter(oldRectangle));

My issue is that I don't know of a way to reference them
As Java is a strong-typed language, to store the references to each Rectangle (or any object) attribute, you must create variables that match the field.
First, you need your rectangle have attributes:
public class Rectangle {
public double width;
public dobule height;
// constructors here...
After, methods to calculate area and perimeter:
public double getArea() {
return (width*height);
}
public double getPerimeter() {
return ((2*width)+(2*height));
}
Now, to reference them (i guess you still mean area and perimeter):
double area1 = getArea(newRectangle);
double area2 = getArea(oldRectangle);
and
double perimeter1 = getPerimeter(newRectangle);
double perimeter2 = getPerimeter(oldRectangle);

There are no width and height properties in your class, they are only defined inside the constructor, declare them in the class and not inside the constructors so you can acces them like this:
public class Rectangle {
double width;
double height;
public Rectangle() {
width = 1;
height = 1;
}
public Rectangle(double w, double h) {
width = w;
height = h;
}
public double getArea(double w, double h) {
return (w*h);
}
public double getPerimeter(double w, double h) {
return ((2*w)+(2*h));
}
//....
}
Note: It's better to declare them as private and use getters and setters to acces them, take a look at Adding Setter and Getter Methods for further information.
EDIT:
In your case you don't need to pass parameters to your methods (because the calculation needs this rectangle width and height), just calculate them using your class fields, like this:
public double getArea() {
return (width*height);
}
public double getPerimeter() {
return ((2*width)+(2*height));
}
Here's what you need to do to acces your variables:
public static void main(String[] args) {
Rectangle oldRectangle = new Rectangle(4, 40);
Rectangle newRectangle = new Rectangle(3.5, 35.9);
//In the following you access all the object variables and methods
System.out.println("Width of Rectangle 1 is: " + oldRectangle.width);
System.out.println("Height of Rectangle 1 is: " + oldRectangle.height);
System.out.println("Area of Rectangle 1 is: " + oldRectangle.getArea());
System.out.println("Perimeter of Rectangle 1 is: " + oldRectangle.getPerimeter());
System.out.println("Width of Rectangle 1 is: " + newRectangle.width);
System.out.println("Height of Rectangle 1 is: " + newRectangle.height);
System.out.println("Area of Rectangle 1 is: " + newRectangle.getArea());
System.out.println("Perimeter of Rectangle 1 is: " + newRectangle.getPerimeter());
}
You can test the DEMO here.
And to answer your question about using constructor, calling the parametrized constructor like this:
Rectangle oldRectangle = new Rectangle(4, 40);
Is equivalent to:
// create the object
Rectangle oldRectangle = new Rectangle();
//And then assigning the values 4 and 40 to its width and height
oldRectangle.width=4;
oldRectangle.height=40;

Related

Lab constructing a rectangle in Java

I am new to programming and recently started on my computer science degree. Due to my son being sick I missed labs yesterday for CS-140/Java and am having a little trouble with my lab assignment from home.
I am told to Construct an empty Rectangle called box.
Figure out how to change the width of box to 50, its height to 60 and top-left corner to [100,50]. (You need to call appropriate methods on box to achieve this.)
Figure out how to compute the area of box. You have to get the height and width of box, by calling appropriate methods to compute the area.
Then print the value returned by calling a method on box and then we print a message that describes the value we expect to see.
I have searched through stack exchange and found some useful information but I still cannot figure out the bugs in the code and why it is not working. I am assuming the 63 errors are from something like a curly bracket in the beginning either missing or too many curly brackets.
I have 63 errors somehow the code I have entered so far is the following:
import java.awt.Rectangle;
public class Rectangle {
public double x;
public double y;
public double width, height;
public Rectangle(double x, double y, double w, double h) {{
this.x = x;
this.y = y;
width = w;
height = h;
}
public static void main(String[] args) {
Rectangle box = new Rectangle (100, 50, 50, 60);
System.out.println(box);
}
System.out.println("Part 1:");
System.out.println("-------");
System.out.println("CREATING AN EMPTY Rectangle, SETTING ITS width TO 50, " +
"ITS height TO 60, AND ITS TOP LEFT CORNER TO (100, 50)");
// Code for Part 1 goes here
}
System.out.println("Part 2:");
System.out.println("-------");
System.out.println("TESTING THE PERIMETER OF THE RECTANGLE "
+ "CREATED IN PART 1 ABOVE");
// Code for Part 2 goes here. Use the same Rectangle
// you used Part1
// define a String reference called river and initialize it
// to Mississippi. Read the API to figure out which method
// to use to get the desired effect.
System.out.println("Part 3:");
System.out.println("-------");
System.out.println("INITIALIZING river to Mississippi AND REPLACING "
+ "EACH i to ! AND EACH s TO $");
// code for Part 3 goes here
System.out.println("Part 4:");
System.out.println("-------");
System.out.println("CONSTRUCTING A StringBuilder OBJECT INITIALIZED "
+ "TO desserts AND REVERSING IT");
// code for Part 4 goes here
System.out.println("Part 5:");
System.out.println("-------");
System.out.println("CONSTRUCTING A Random OBJECT TO PLAY LOTTERY BY GENERATING ");
System.out.println("6 RANDOM INTEGERS BETWEEN 1 and 49 (BOTH INCLUSIVE)");
//code for Part 5 goes here
System.out.println("Part 6:");
System.out.println("-------");
System.out.println("ADDING ONE DAY TO 2/28/2019, 2/28/2020, 2/28/2021 " +
"AND 2/28/2022 AND PRINTING THEM");
// code for Part 6 goes here
}
}
Any help is appreciated. I am excited to join the community of StackOverflow and hopefully be able to contribute someday.
Here is the cleanup of your code:
//import java.awt.Rectangle; // you probably autocompleted this line, since you created your own Rectangle class for console outputs
public class Rectangle {
public double x;
public double y;
public double width, height;
public Rectangle(double x, double y, double w, double h) {
this.x = x;
this.y = y;
width = w;
height = h;
}
public static void main(String[] args) {
Rectangle box = new Rectangle (100, 50, 50, 60);
System.out.println(box);
System.out.println("Part 1:");
System.out.println("-------");
System.out.println("CREATING AN EMPTY Rectangle, SETTING ITS width TO 50, " +
"ITS height TO 60, AND ITS TOP LEFT CORNER TO (100, 50)");
// Code for Part 1 goes here
System.out.println("Part 2:");
System.out.println("-------");
System.out.println("TESTING THE PERIMETER OF THE RECTANGLE "
+ "CREATED IN PART 1 ABOVE");
// Code for Part 2 goes here. Use the same Rectangle
// you used Part1
// define a String reference called river and initialize it
// to Mississippi. Read the API to figure out which method
// to use to get the desired effect.
System.out.println("Part 3:");
System.out.println("-------");
System.out.println("INITIALIZING river to Mississippi AND REPLACING "
+ "EACH i to ! AND EACH s TO $");
// code for Part 3 goes here
System.out.println("Part 4:");
System.out.println("-------");
System.out.println("CONSTRUCTING A StringBuilder OBJECT INITIALIZED "
+ "TO desserts AND REVERSING IT");
// code for Part 4 goes here
System.out.println("Part 5:");
System.out.println("-------");
System.out.println("CONSTRUCTING A Random OBJECT TO PLAY LOTTERY BY GENERATING ");
System.out.println("6 RANDOM INTEGERS BETWEEN 1 and 49 (BOTH INCLUSIVE)");
//code for Part 5 goes here
System.out.println("Part 6:");
System.out.println("-------");
System.out.println("ADDING ONE DAY TO 2/28/2019, 2/28/2020, 2/28/2021 " +
"AND 2/28/2022 AND PRINTING THEM");
// code for Part 6 goes here
}
}
The assignments are as follows:
//assignment 1
Rectangle box = new Rectangle(0,0,0,0);
//assignment 2
box.width = 50;
box.height = 60;
box.x = 100;
box.y = 150;
//assignment 3
int area = box.height*box.width;
//assignment 4
System.out.println("Area: "+area);
I'm sure you can integrate this into your own code and make the appropriate methods as well as getters and setter if needed.
The answers to all of these questions can be found on the Java documentation for Rectangle. I don't want to spoonfeed, so here's some of my observations.
Use one of the constructors to set dimensions.
Use some of the methods to read each dimension (height, width, etc)
Calculate using formula for area.

Creating an abstract class to get perimeter and area?

The problem I was given:
Write an abstract superclass encapsulating a shape: a shape has 2 abstract methods: one returning the perimeter of the shape, another returning the area of the shoe. It also has a constant field named PI. This class has two non-abstract subclasses: one encapsulating a circle, and the other encapsulating a rectangle. A circle has one additional attribute, its radius. A rectangle has 2 additional attributes, its width and height. You also need to include a client class to test these two classes.
Here's the work I've done:
Shape.java
public abstract class Shape
{
public abstract double getPerimeter();
public abstract double getArea();
}
Circle.java
public class Circle extends Shape
{
private double radius;
final double pi = Math.PI;
//Defualt Constructor, calls Shape default constructor
public Circle()
{
//Set default value to radius
this.radius = 1;
}
public Circle(double radius)
{
this.radius = radius;
}
public double getArea()
{
//Return πr^2 (area formula)
//Use Math.pow method (page 141) in order to calculate exponent
return (pi * Math.pow(radius, 2));
}
public double getPerimeter()
{
//Return 2πr (perimeter formula)
return (2 * pi * radius);
}}
Rectangle.java
public class Rectangle extends Shape
{
private double width, height;
public Rectangle()
{
//set default value to width and height
this.width = 1;
this.height = 1;
}
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public double getArea()
{
return width * height;
}
public double getPerimeter()
{
return 2 * (width + height);
}}
ShapeClient.java
public class ShapeClient {
public static void main(String [] args)
{
// To test Rectangle...
double width = 13, length = 9;
Shape rectangle = new Rectangle(width, length);
System.out.println("The rectangle width is: " + width
+ " and the length is: " + length
+ "The area is: " + rectangle.getArea()
+ "and the perimeter is: " + rectangle.getPerimeter() + ".");
//To test Circle...
double radius = 3;
Shape circle = new Circle(radius);
System.out.println("The radius of the circle is: " + radius
+ "The area is: " + circle.getArea()
+ "and the perimeter is: " + circle.getPerimeter() + ".");
}}
My question is: Does the constant field for PI need to be in the Shape class rather than the Circle class? If so, how should I about taking it out of the circle class and how should I place it in the Shape class?
The abstract class should only contain fields & methods that are general to all shapes such as getArea and getPerimeter.
In this case PI is only specific to the Circle shape or to rephrase, the square has no use for the constant PI. PI should therefore only reside in the 'Circle' class and not the Shape class.
The PI attribute definitely needs to be on the Circle class. The abstract Shape class should contain attributes and methods that all of its sub-classes are going to use or implement. In this case, the Rectangle class has no need for the PI attribute.
just move the constant to the abstract class.

Why is the initial value changing and not the objects value?

This is going to be quite long winded as I'm still relatively very new to Java as a language.
This program has a Class called Point. This creates Points for vertices of shapes.
public class Point {
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
In this class, there are methods such as distance (between 2 points), scale(increases by factor), translate(takes an x and y coordinate and adds it to this.x and x.y) and so on.
I then have 3 more classes to create shapes. Triangle, Rectangle and Circle, where the constructors look like this.
public class Triangle {
private int sides;
private Point[] points;
public Triangle(Point[] vertices) {
this.sides = 3;
this.points = vertices;
}
.
public class Rectangle {
private int sides;
private Point topCorner;
private int width;
private int length;
public Rectangle(Point corner, int w, int l){
this.sides = 4;
this.topCorner = corner;
this.width = w;
this.length = l;
}
and
public class Circle {
private Point center;
private int radius;
public Circle(Point center, int radius){
this.center = center;
this.radius = radius;
}
All these classes have the same methods translate, and scale. An example of which is shown here.
//For the Rectangle Class
public void translate(int dx, int dy){
topCorner.translate(dx, dy);
}
My problem is in my main class. What happens is I created 3 points, and used all 3 as an array to create the triangle, and 2 others as points for the rectangle and for the circle. Now when I call the translate method on all 3 objects in one go, it ends up doubling the value, as I believe my mistake is that I have passed a reference to "p1" "p2" and "p3" somewhere, and I am changing their values instead of the objects values. Here is the code, and I will explain the output after
public class GraphicsDemo {
public static void main(String[] args) {
Point p1 = new Point(0,20);
Point p2 = new Point(20,0);
Point p3 = new Point(30,30);
Point[] vertices = {p1,p2,p3};
Triangle t = new Triangle(vertices);
Rectangle r = new Rectangle(p1,10,15);
Circle c = new Circle (p2, 25);
System.out.println("Triangle" + "\n" + t.toString() + "\n" + "area:" + t.area() + "\n" + "perimeter: " + t.perimeter());
System.out.println("Reactangle" + "\n" + r.toString() + "\n" + "area:" + r.area() + "\n" + "perimeter: " + r.perimeter());
System.out.println("Circle" + "\n" + c.toString() + "\n" + "area:" + c.area() + "\n" + "perimeter: " + c.perimeter());
c.translate(10, 15);
t.translate(10, 15);
r.translate(10, 15);
System.out.println("Triangle" + "\n" + t.toString() + "\n" + "area:" + t.area() + "\n" + "perimeter: " + t.perimeter());
System.out.println("Reactangle" + "\n" + r.toString() + "\n" + "area:" + r.area() + "\n" + "perimeter: " + r.perimeter());
System.out.println("Circle" + "\n" + c.toString() + "\n" + "area:" + c.area() + "\n" + "perimeter: " + c.perimeter());;
The output for this is that instead of adding 10 and 15 to a shapes coordinates, 20 and 30 are added if the point is used in more than one shape. I'm sure that this is because I'm actually changing the value of the points instead of the objects, but I have no idea how to change this.
Thank you to anyone that can help in advance. This is the first time in my experience where I have tried a lot of things and am up against a wall.
You missed to show the most important part of your code, however it looks like your analysis is correct. In your translation code you actually need to generate new point instances (and replace them).
This is generally a good idea to not modify objects but keep them immutable. Best way to ensure this is to skip the setters:
class Point {
Point(int x, int y) { this.x = x; this.y = y; }
int getX() { return x; } intGetY() { return y; }
/** Create a new point displaced by given coordinates. */
Point translate(int deltaX, int deltaY)
{
return new Point(this.getX() + deltaX, this.getY() + deltaY);
}
}
They are indeed the same object. I.e Triangle t has p1. If you change Rectangle p1 you are changing triangle p1 as well.
You should do deep clones in Point's for them to be independent.
You assumption is correct, you are passing references. Circle, Triangle, Rectangle are all taking one or more points in common with the other shapes in their constructor. See rectangle which takes the same point (p1) as triangle.
Point[] vertices = {p1,p2,p3};
Triangle t = new Triangle(vertices);
Rectangle r = new Rectangle(p1,10,15);
Circle c = new Circle (p2, 25);
A simple solution is to clone the points in the constructors as I did in the Triangle class below. This means the two shapes will share the same x and y to start with, but changes to one shape will no longer directly affect the other.
A class is an object reference. So you need to create a new Object reference to create separate objects to work on. This is what the .clone() method I added to you point class does, it copies the internals of point and creates an exact copy. The constructors of the other methods then invoke the clone method on the points you feed them, so that they are only working on copies of the points you give them.
class Point{
public int x;
public int y;
Point(int x, int y){
this.x = x;
this.y = y;
}
public Point clone(){
return new Point(x,y);
}
}
class Triangle{
final static int m_sides = 3; //constant
Point[] m_points;
Triangle(Point[] points){
//You need to clone your ponits.
m_points = new Point[]{
points[0].clone(),
points[1].clone(),
points[2].clone()};
}

Inherits in Java

class Box
{
// Instance Variables
double length, ipsos;
double width, mikos;
double height, platos;
// Constructors
public Box ( double side )
{
width = side;
height = side;
length = side;
}
public Box ( double x , double y , double z)
{
platos = y;
ipsos = z;
mikos = x;
}
// Methods
double calculate(double praksi)
{
return 2 * ( width * height +
width * length +
height * length ) ;
}
double volume(double emvadon)
{
return platos * ipsos * mikos;
}
#Override
public String toString() {
return "Volume: " + volume(1) + "\n Calculate: " + calculate(1);
}
}
How can we create a class that inherits MyBox class Box and will be used only for cubes by writing a constructor to ensure the creation of a cube using the second constructor of Box that takes three arguments and in case of an error initializing the cube MyBox to print error message?
I am very new at java, so please explain as simple as possible.
I'm a little confused by why Box has two constructors, and six fields. I would have thought that one constructor and three fields would be enough. But assuming you keep the constructor with three parameters, you can call it from your Cube constructor like this.
The line starting super specifies which Box constructor the Cube constructor should call, and what to pass it. This guarantees that a Cube will always have all three dimensions equal.
public class Cube extends Box {
public Cube(double side) {
super(side, side, side);
}
}

Java OBJECTS and Classes beginner

Hey guys so we just started covering objects and classes in my class. I understand creating a new instance of the class pretty well. Howerver, its the data fields and methods im having trouble comprehending. Here is a sample from my book i wrote out. I dont quite get the part where i commmented: "//construct a circle with radius 1. Reason being b.c i declared the double radius in the SimpleCircle class already, so why would i need to write SimpleCircle again? I somewhat understand the accessors and mutators of this program but would like a bit more simple clarification on all this please.
public class TestSimpleCircle {
public static void main(String[] args) {
SimpleCircle circle1 = new SimpleCircle();
System.out.println("The area of the circle of radius " + circle1.radius + " is " + circle1.getArea());
// create a circle with radius 25
SimpleCircle circle2 = new SimpleCircle(25);
System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
// create a circle with radius 125
SimpleCircle circle3 = new SimpleCircle(125);
System.out.println("The area of the circle of radius " + circle3.radius + " is " + circle3.getArea());
// Modify circle radius of second object
circle2.setRadius(100); //or circle2.setRadius(100);
System.out.println("The area of the circle of radius " + circle2.radius + " is " + circle2.getArea());
} // end main
} // end class
class SimpleCircle {
double radius;
// construct a circle with radius 1
SimpleCircle() {
radius = 1;
}
// construct a circle with a specified radius
SimpleCircle(double newRadius) {
radius = newRadius;
}
// return the are of this circle
double getArea() {
return radius * radius * Math.PI;
}
// return the perimeter of this circle
double getPerimeter() {
return 2 * radius * Math.PI;
}
// set a new radius for this circle
void setRadius(double newRadius) {
radius = newRadius;
}
} // end class
The reason you have two SimpleCircle() statements is because the one is the default constructor, which you technically could omit if you changed double radius; to double radius = 1;. The second allows for the developer to pass a parameter to SimpleCircle(double) of type double and assign it to the field called radius. Both SimpleCircle(...) statements are known as constructors.
Sample output of your program:
The are of the circle of radius 1.0 is 3.141592653589793
The are of the circle of radius 25.0 is 1963.4954084936207
The area of the circle of radius 125.0 is 49087.385212340516
The area of the circle of radius 100.0 is 31415.926535897932
You can see in the first sentence, it used the default constructor which sets the radius equal to 1 or 1.0 because it is a double. The rest use the passed in value for radius or the second constructor.
Because you never assigned your field variable a value in the declaration statement. If you did, then you would not need to set it equal to 1 in the constructor. I hope that answers your question.
This
class SimpleCircle {
double radius;
// construct a circle with radius 1
SimpleCircle() {
radius = 1;
}
Will lead to the same output as this
class SimpleCircle {
double radius = 1;
// construct a circle with radius 1
SimpleCircle() {
}

Categories