-2

As the title,

Assume that there's a KiahApplication class that extends Application,

I've seen the code below:

KiahApplication Kapp=(KiahApplication)getApplication();

But isn't it incorrect to cast a superclass to its subclass?

Thank you so much for helping!

  • 1
    It's correct if it's actually an instance of the subclass. – Oliver Charlesworth Jul 03 '16 at 11:45
  • ...and in case it's not you'll get a `ClassCastException` at runtime. But it is perfectly ok to cast if you know what you are doing. – Hulk Jul 03 '16 at 11:46
  • @OliverCharlesworth thank you so much! I should've thought of it. lol – Kiah Starck Jul 03 '16 at 12:08
  • @Hulk You mean we can just ignore it by try-catch and it'd still work? Should it be an error exception? – Kiah Starck Jul 03 '16 at 12:11
  • If you are not sure if the cast will actually work, you should prefer checking the type by using the `instanceof` - operator. Catching the Exception would involve a lot of unnecessary overhead. – Hulk Jul 03 '16 at 13:33

1 Answers1

2

No, it's not illegal and sometimes is necessary. The important thing is to be sure that the object is an instance of the subclass. You can do this by testing it in code or by catching the potential ClassCastException. In the example you give, if you are absolutely sure that the Application object is of the right type then you could leave as is.

Grayman
  • 629
  • 4
  • 14
  • Thank you so much & understood, so it's actually a polymorphism. But why bothers? It returns in Application type & we need to cast it again. – Kiah Starck Jul 03 '16 at 12:30
  • The Activity method getApplication() has a return type of Application since it is obviously unaware of any custom subclasses. You don't have to cast the result if you only want to call the methods defined by Application. However, if you have defined new methods in KiahApplication (e.g. for global state) they will not be visible using an object reference of type Application. That's when you need to cast to a reference of type KiahApplication. – Grayman Jul 04 '16 at 17:28