-2

This is a test question. I can add to the [???] but can't edit the rest of the code. What should I add?

class Primary{Primary(String name){this.name=name;}String name;}

class Secondary extends Primary{[?????]}

public class Exercise{

  public static void main(String [] arg){
    assert (!new Secondary().name.equals(new Secondary().name));
  }
}

2 Answers2

4

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

Community
  • 1
  • 1
candied_orange
  • 7,036
  • 2
  • 28
  • 62
0

In my opinion, your question is not clear. The asseration may be always false, except that you change the constructor of the B.

public class Test {
 class A{
     String name;
     A(String name){
         this.name = name;
     }
 }

 class B extends A{
     B(String name){
         //super(name + "something else"); //asseration will be true.
         super(name);
     }
 }

 public static void main(String[] args){
     Test t = new Test();
     A a = t.new A("uttp");
     B b = t.new B("uttp");

     System.out.println(!a.name.equals(b.name));
 }
}
uttp
  • 92
  • 6