danger mouse
danger mouse

Reputation: 1497

Java superclass catch and subclass catch

I am confused. Are the following two statements accurate?

  1. An object of a class has no knowledge of, or access to, any of its subclasses.

  2. On the topic of exception handling, a superclass catch will catch all of its subclasses.

I think there's some logic that I'm not seeing. In 1 the superclass has no knowledge of the subclass, whereas in 2 the superclass does have knowledge of the subclass. Any clarification on this would be appreciated.

Upvotes: 1

Views: 2455

Answers (3)

user4439670
user4439670

Reputation:

The super class itself has no knowledge of its sub-classes, but the jvm has that knowledge, and jvm is doing the work for exception handling, polymorphism etc.

Upvotes: 1

SMA
SMA

Reputation: 37023

Yes that's right.

  1. An object of a class has no knowledge of, or access to, any of its subclasses.

    Object is the parent class. Consider it similar to real world parents who doesn't know in advance how many childrens they are going to have and what extra features they are going to have or what they are going to do apart of what i have already have i.e. the same feature with Object class i.e. equals/hashCode/wait/notify etc. So it safely assumes either my childs would override say equals if not Object class is there to handle everything for these existing features.

  2. On the topic of exception handling, a superclass catch will catch all of its subclasses.

    Yes. Again consider the same example as above. People says "Jr. xyz how are you?" People know you as well and can greet you like "Hi pqr" and people know you with your parents name as well. Similar is the concept here. If it see's the exact match in catch block, its going to execute the same block else it will goto it's parent catch block.

Upvotes: 0

yole
yole

Reputation: 97168

Both of the statements are true. When a "catch" clause is executed, it gets a specific instance of an exception. It can look at the superclasses of that instance and check if any of those superclasses matches the class specified in the "catch" clause. There is no need for it to check all the possible subclasses of the class specified in the "catch" clause, so statement 1 holds true.

Upvotes: 0

Related Questions