Actual class of object reference

3.7k views Asked by At

Given three classes A, B, and C, where B is a subclass of A, and C is a subclass of B.

(a) (o instanceof B) && (!(o instanceof A))
(b) (o instanceof B) && (!(o instanceof C))
(c) !((o instanceof A) || (o instanceof B))
(d) (o instanceof B)
(e) (o instanceof B) && !((o instanceof A) || (o instanceof C))

Question: Which option is true only when an object denoted by reference o has actually been instantiated from class B?

Note: I am unable to understand the question. Even though the object is instantiated from B, we can instantiate objects from any of the classes A, B or C.

What is the question exactly trying to state?

2

There are 2 answers

0
NickJ On BEST ANSWER

Since this is clearly a homework exercise, it is not appropriate for me to provide an answer directly. Instead, I have written a little program for you to demonstrate what the question means, and running it will provide an answer.

You can try this out for yourself:

public class Main {

  class A {}
  class B extends A {}
  class C extends B {}

  public static void main(String[] args) {
    new Main().experiment();
  }

  private void experiment() {
    Object o = new B();

    boolean a = (o instanceof B) && (!(o instanceof A));
    boolean b = (o instanceof B) && (!(o instanceof C));
    boolean c = !((o instanceof A) || (o instanceof B));
    boolean d = (o instanceof B);
    boolean e = (o instanceof B) && !((o instanceof A) || (o instanceof C));

    System.out.println("a = "+a);
    System.out.println("b = "+b);
    System.out.println("c = "+c);
    System.out.println("d = "+d);
    System.out.println("e = "+e);
  }

}
0
almightyGOSU On

If you do not understand instanceof, read this.

The example provided explains what you are asking quite clearly.

  • Is a superclass an instanceof a subclass? No
  • Is a subclass an instanceof a superclass? Yes

From the question, you know the relationships between A, B, C.
Since o 's actual class is B, you should be able to answer those questions with the given information.