Friday, July 31, 2009

What is wrong with the following Java code? (Emphasis on Polymorphism)?

Given the following classes and their objects:


class Class1 {}


class Class2 extends Class 1{}


class Class3 extends Class 1{}





Class2 c2 = new Class2();


Class3 c3 = new Class3();





Analyze the follow Statement:


c2 = (Class2) ( (Class1) c3 );





A) Classes cannot be cast.


B) The casting will compile and run successfully.


C) A runtime error will occur b/c you cannot cast objects from sibling classes.


D)A runtime error will occur b/c both parent class and child class cannot be in the same statement.


E) None of the above.








This is problem I must figure out in my Computing class. I'm trying to look in the book for the answer but it's not that simple.

What is wrong with the following Java code? (Emphasis on Polymorphism)?
Something I find useful is to assign real-life objects to the classes. So let's say Class1 is a class Vehicle(), with classes 2 and 3 being Car() and Truck() respectively. So we make a Car() and Truck() and store them in c2 and c3. Assuming that classes can be cast (since some previous posts already told you this), you can think about this in a more real world sense. "(Class1) c3" casts c3 as an instance of Class1. In other words, it casts a Truck() as a Vehicle(), which should make sense in real life. Then it tries to cast what we have, a Vehicle(), as a Car() and then stores it in a variable of type Car(). Without giving the answer, try to take this and see if the rest will work. Will it compile? Will it run? Hope this helped at all...
Reply:There is a *reason* it's not that simple: because you're supposed to figure it out for yourself. That's probably the biggest part of computer programing: figuring out how to solve problems on your own.





With that said, try to eliminate some of the answers that you know can't be. I'll start you off: (A) is dead wrong.
Reply:It's not A.

video cards

No comments:

Post a Comment