Here's an answer that strictly makes changes only to the [???] part of your question:
class A{A(String name){this.name=name;System.out.println(name+" <-- name");}String name;}
class B extends A{
static int instanceCount = 0;
public B() {
super(instanceCount++ % 2 == 0 ? "CandiedOrange" : "uttp");
}
}
public class Exercise{
public static void main(String [] arg){
//assert(false);
assert (!new B().name.equals(new B().name));
}
}
Outputs:
CandiedOrange <-- name
uttp <-- name
What's happening is the static instanceCount
int's value is being shared among all B
instances. They all point to the same bit of memory. If it wasn't static each B
instance would get their own memory for instanceCount and none of them would ever have a value greater than 1.
Since instanceCount
gets incremented every time an instance of B
is constructed it's keeping track of how many B
instances there are.
The % 2
means divide by two and tell me the remainder. The remainder will always be 1 or 0. When it's 0 you get my name. When it's 1 you get uttp's. These names are not equal so the assert will pass. The ! negates the rest which is only true when they are equal. Thus, it asserts the names should not be equal.
I did say I'd only change what was in the [???] but you can remove the println
since it's just debugging code.
Make sure the test fails when you remove the comment in front of assert(false)
. If not you likely need to add -ea to your vm arguments: https://stackoverflow.com/a/5509180/1493294