Object Oriented Programming Tutorial - Part Five, November 2002
Well I hope you have had a rest and some time to digest what we have covered so far. We have gone a long way in a very short period of time. Before we go any further let's take a quick look back to make sure we have as much digested as possible from the last page.
- An object may be created using a superclass type as the Class variable
- The JVM waits until run time to decide which method is to be called in a given situation
- When a subclass is cast into a superclass and the subclass overrides one of the superclass's methods, the method from the subclass will be called
- In the above situation an overridden variable (in the subclass) will be ignored in favor of the superclass variable
OK, now let's cover a few rules about what we have seen here. First of all a superclass cannot be assigned to a subclass such as this:
Dog d = new Animal();
Why? ......Think about it. By attempting to do this we are saying an Animal IS A Dog which just doesn't make any sense at all. Secondly all of the variables would not be initialized even if we used the Animal's second constructor. You can however do this:
Dog d = (Dog)new Animal();
It will compile BUT will throw a ClassCastException at run time for the same reasons as the example above! Also you may NEVER cast across the hierarchy tree! In other words this is a BIG no-no:
Dog d = new Elephant();
Plain and simple the rules there for very logical reasons and when you look at some of these no-nos you will see why they would never work. If you always remember to cast up the hierarchy tree (to the superclass) you will never go wrong!
Just to make your head hurt a tad more (I have to cover these) here are several other rules that apply to this type casting. We won't cover them in detail right now but you should be aware they exist.
- Casting a class to an interface requires the class implement that interface
- Casting an interface to an interface requires the interface being cast be a sub-interface of the interface it's being cast to.
Well I really hope this helped you understand some of these concepts a little better than when you started. Objects can be a frustrating topic but don't give up......it get's better!
Theresa Judd, permanentcosmeticsbytheresa.com | More Testimonials >>