More OOP: Objects and Constructors Here, we will continue our discussion of obje
ID: 3794366 • Letter: M
Question
More OOP: Objects and Constructors
Here, we will continue our discussion of objects. Suppose that you have a class with
multiple attributes. As a simple example, imagine a class called Point3D that holds three public variables: x, y,
and z, which are the coordinates of a point in space. Suppose that you want to create a point, and set its
coordinates to (3.0, 4.0, 5.0). You could do it as follows:
Point3D p = new Point3D();
p.x = 3.0;
p.y = 4.0;
p.z = 5.0;
However, this takes 4 lines of code. Instead of going through that sequence, it is possible to write a special
method called a constructor that will initialize the Point3D with three values when it is created. A constructor is
simply a method that (1) has no return value, and (2) has the same name as the class. For example, a constructor
with one parameter for Point3D that sets all three coordinates to the same value could be written:
public Point3D(double a)
{
x = a;
y = a;
z = a;
}
You cannot call a constructor directly. Instead, it gets called when you create an object using the keyword new.
For example, if you make a constructor with three parameters for Point3D, you can write the following code to
initialize several points:
Point3D p = new Point3D(3.0, 4.0, 5.0);
Point3D q = new Point3D(6.0, -7.0, 8.2);
Each one of these replaces 4 lines of code, making it easier to type and read.
Part 10)
Write the class Point3D in a file called Point3D.java. Use the following directions:
a) Give the class 3 public double variables: x, y, and z.
b) Write a public constructor that takes 3 double variables: xx, yy, and zz.
(I'm not naming them x, y, and z so as not to conflict with the instance variables.)
c) Make sure that your file compiles. (Note that it will not run since it does not have a main method.)
Explanation / Answer
public class Point3D {
public double x, y, z;
public Point3D(double xx, double yy, double zz){
x = xx;
y = yy;
z = zz;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.