This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Consider the inhertance hierarchy in the diagram The base class Shape is an interface here. Polygon and Circle implement interface Shape. Triangle and Square are subclass of Polygon Now let's look at a range of straightforward declarations Polygon polygon = new Polygon(); Circle circle = new Cirle(); Triangle triangle = new Triangle(); Square square = new Sqaure(); But we can also declare an object reference and intialize it to contain any of it's subclasses. Shape s2 = new Polygon(); Shape s3 = new Triangle(); Shape s4 = new Circle(); Shape s5 = new Square(); Because a Shape is any Shape (Polygon, Circle, Triangle or Square) We can also say Triangle t1 = new Triangle(); Shape s6 = t1; This is upcasting or moving up the inheritance hierarchy. Which means we declare an object reference of the base-type or it's interface and assign to it an object of the subclass or class that implements the interface Simple and easy as long as we don't violate the lines of inheritance For example, you can't declare or cast a Square into a Circle Circle c1 = new Square(); Downcasting is moving down the hierarchy and requires an explicit cast. You can downcast as far down the hierarchy as the ACTUAL object created. Square sq = (Square) s5 ; Polygon poly = (Square) s5 ; So for your 2 statements (1)A a = new A(); (2)B b = (B) a; (2) will not work because a is actually an object of type A. However, if you wrote A a = new B(); B b=(B) a; it would. You should write a lot of small programs and play around with these concepts regards, Jyotsna </pre> </body> </head> </html>
[This message has been edited by Jyotsna Clarkin (edited May 10, 2001).]