KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
In the example below (from my coursepack), we want to give to the Square instance c1 the reference of some other object p1 , but only if those 2 are of compatible types. if (p1 instanceof Square) {c1 = (Square) p1;} What I don't understand here is that we first check that p1 is indeed a Square , and then we still cast it. If it's a Square , why cast? I suspect the answer lies in the distinction between apparent and actual types, but I'm confused nonetheless... Edit: How would the compiler deal with: if (p1 instanceof Square) {c1 = p1;} Edit2: Is the issue that instanceof checks for the actual type rather than the apparent type? And then that the cast changes the apparent type?
Tags (comma-separated)
Save Edits
Cancel