-2

I saw this from a book

class AAA {

}

class BBB extends AAA {


    public static void main(String[] args) {
        BBB bb = new BBB();
        System.out.println(bb.equals((AAA) bb));  // true
        System.out.println(bb.equals((BBB) bb));  // true
    }
}

Simply speaking, BBB is a subclass of AAA.

but when an instance of BBB bb is created, I saw the className in bracket before the instance being used somewhere else. So I tested the equality, it seem that bb is the same as both ((AAA) bb) and ((BBB) bb).

So why is this used? What is the purpose?

Thanks,

jxie0755
  • 1,682
  • 1
  • 16
  • 35

1 Answers1

1

What are you seeing here is Casting, in this case, explicit casting, because you are telling the compiler that "bb" will be an instance of class "AAA". This let you call specific "AAA" class methods even when "bb" is instanciated as a "BBB" class. If you want more information you can read oracle docs about "Polymorphism" and "Casting".

See "Casting Objects" in this link:

"Inheritance" Oracle Docs

Edit by JP
There is however, a quite pervert situation, when public fields get hidden in children classes. In this case, you should cast to the parent class in order to reach the hidden fields (which might be of different type than as declared in children).

See:
https://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html
Java inheritance and hidden public fields

Joe Public
  • 67
  • 1
  • 8
Marco Marchetti
  • 187
  • 1
  • 6
  • 14
  • But since BBB is a subclass of AAA, so bb will automatically inherit all the methods from AAA, why do I need casting then? – jxie0755 Feb 08 '19 at 20:19
  • 1
    @Code_Control_jxie0755 You dont. You are comparing the same object with itself. the cast doesnt make sense, the whole example doesnt make much sense either. To be precise: the cast doesnt change anything here. A cast doesnt change the runtime nature of an object! – GhostCat Feb 08 '19 at 20:23