In this example, why is it still necessary to typecast an object to be sure of its type, even after getClass() has been called?

前端 未结 4 1065
长发绾君心
长发绾君心 2021-01-28 16:20

I\'m following this MOOC on OOP in Java and it has presented an example I don\'t fully understand. In the example, a Book class has been created and they are const

4条回答
  •  悲哀的现实
    2021-01-28 17:00

    Casting a variable to a data type basically is telling the compiler "Trust me, I know what I'm doing." In the case of casting an "Object" to "Book", you are assuring the compiler that the object is, in fact, a Book and to proceed accordingly. It also as the effect of forcing you to believe you know what you are doing.

    Edit: I'm not sure if you are asking why you needed the actual cast (adding "(Book)") or why you needed to make the assignment to a Book variable. I answered the former. If the question is the latter, the answer is you need the Book variable so the Book methods are available.

    Since you have the tools to make the determination, you would think that the cast is not necessary since the compiler is capable of generating the same code you use to make the determination, requiring you to just make the assignment:

    Book book = object;           // Wrong
    

    instead of

    Book book = (Book) object;    // Right
    

    If you expect the compiler to "just know" that the Object is a Book, then the compiler will have to test the Object each time you use a Book method. By explicitly telling it in the assignment, the compiler can create code specific to the Book class without any further examination of the Object.

提交回复
热议问题