Example with a Point class:
class Point
{
double x; //x coordinate of this point.
double y; //y coordinate of this point.
Point(double xParam, double yParam)
{
x = xParam;
y = yParam;
}
void print()
{
System.out.println("Point ( "
+
this.x + ", "
+
this.y + ")");
}
double getX() {return this.x;}
double getY() {return this.y;}
void setX(double xParam) { this.x = xParam; }
void setY(double yParam) { this.y = yParam; }
Point flipped()
{
Point ret = new Point(this.getY(), this.getX());
return ret;
}
}
class PointDemonstrator
{
public static void main(String[] args)
{
Point varA = new Point(0.0, 0.0);
Point varB = new Point(33.3, 75.0);
System.out.print("via varA:");
varA.print();
System.out.print("via varB:");
varB.print();
WHAT IS PRINTED?
varA = varB;
System.out.println("\n After varA = varB; ");
System.out.print("via varA:");
varA.print();
System.out.print("via varB:");
varB.print();
WHAT IS PRINTED?
varA.setX(-598.2);
System.out.println("\n After varA.setX(-598.2); ");
System.out.print("via varA:");
varA.print();
System.out.print("via varB:");
varB.print();
WHAT IS PRINTED?
} }Example with an array:
class ArrayDemonstrator
{
public static void main(String[] args)
{
double aryA[] = new double[2];
double aryB[] = new double[2];
aryA[0] = 0.0;
aryA[1] = 0.0;
aryB[0] = 33.3;
aryB[1] = 75.0;
System.out.println("aryA[0] is " + aryA[0] +
" aryA[1] is " + aryA[1]);
System.out.println("aryB[0] is " + aryB[0] +
" aryB[1] is " + aryB[1]);
WHAT IS PRINTED?
aryA = aryB;
System.out.println("\n After aryA=arB:");
System.out.println("aryA[0] is " + aryA[0] +
" aryA[1] is " + aryA[1]);
System.out.println("aryB[0] is " + aryB[0] +
" aryB[1] is " + aryB[1]);
WHAT IS PRINTED?
aryA[0] = -598.2;
System.out.println("\n After aryA[0] = -598.2");
System.out.println("aryA[0] is " + aryA[0] +
" aryA[1] is " + aryA[1]);
System.out.println("aryB[0] is " + aryB[0] +
" aryB[1] is " + aryB[1]);
WHAT IS PRINTED?
System.out.println(); } }
Exercise: The fact that a Point has two fields (data members) and the array has two entries is irrelevant to the issue these programs demonstrate. Rewrite the programs so they demonstrate the same issue in a simpler way, with only one field or entry.
(The best answer must have a class with only one field and an array of dimension 1. Even though most classes and arrays you will encounter have many fields and entries, there is no rule that they must have more than one. Furthermore, Java allows classes and arrays with zero fields and zero length. Thought question: How can a class with no fields be useful? How can a length zero array be useful?)
Exercise: Will this example change if the data members of the Point class were declared public? What if they were declared private?
Exercise: Find out and report what code can access a class member that is declared neither private nor public.
There has been error in communication with booki server. Not sure right now where is the problem.
You should refresh this page.