I have a question that was in an older test and I need to know the answer for practicing.
We have the following Class:
public class First{
private int num1 = 0;
private int num2 = 0;
private static int count = 0;
public First(int num){
this(num,num);
count++;
System.out.println("First constructor1");
}
public First(int num1, int num2){
this.num1 = num1;
this.num2 = num2;
count++;
System.out.println("First constructor2");
}
public int sum(){
return num1 + num2;
}
public static int getCount(){
return count;
}
}
Now we are operating the following orders:
1. First f1 = new First(10);
2. First f2 = new First(4,7);
3. System.out.println("sum1 = " + f1.sum());
4. System.out.println("count = " + First.getCount());
5. System.out.println("sum2 = " + f2.sum());
6. System.out.println("count = " + First.getCount());
I need to write down the lines that will be printed on screen after those 6 lines.
I know that after the first 3 lines it should be like this:
First constructor2
First constructor1
First constructor2
sum1 = 20
The only thing that disturb me is, what’s the meaning of a line like line #4? is it a method that operate on the class itself instead on an object?
Another question is that in part B we need to re-define the method equals inside the ‘First’ class (same method that extends Object) so she will be able to compare between the object that the method operates on and another ‘First’ type object. The method returns true if both num1, num2 are equals.
I thought about something like this:
public class First {
...
...
.
.
.
public boolean equals (First anotherObj){
if ((First.num1 == anotherObj.num1) && (First.num2 == anotherObj.num2))
return true;
return false;
} // equals
} // 'First' class
Am I right?
Yes, getCount() is a static method of your class First which can be called without instantiating any concrete objects. So in your example by using this method you can read the static variable count, which gets increased by 1 whenever the constructor gets called. So if once you created f1 and f2 count will be 2. “count” is a variable shared by all your First instances.
Your equals() method doesn’t work since first of all you need to override
Secondly, num1 and num2 are private so you need a Getter to make them available.
Something like:
If you override equals you should also override public int hashCode()
Example for hashCode():
}
(5 and 31 are primes, you can also use e.g. Eclipse to automatically generate this methods).