Code Explanation
class A
{
public A()
{
}
void Method1()
{
}
}
class Bextends Aimplements E
{
public B()
{
//super(10);
}
void Method1()
{
}
publicvoid Test1()
{
}
}
class Cextends A
{
public C()
{
//super(10);
}
}
class Dextends B{}
interface E
{
publicvoid Test1();
}
publicclass Test
{
publicstaticvoid main(String[] args)
{
A a =new D();
C c =new C();
E e = (E)a;
B b = (B)e;
}
}
I was wondering what is the purpose of doing E e = (E)a;
and B b = (B)e;
//Are these lines mandatory and what kind of purpose they are solving....
[2374 byte] By [
Harsimrata] at [2007-11-27 0:50:26]

that code is just playing with polymorphism/providing a simple example of polymorphism.
A a = new D() -> you're using a variable of class A to hold an instance of class D, this is possible because D extends B which extends A (therefore, A is a superclass of D)
C c = new C() -> no explanation needed
E e = (E)a; -> remember that a holds an instance of class D (not class A). Class D extends class B. Class B implements interface E, ergo you can use a variable of type E to refer to an instance of type D (casting it from type A to type E provides you with access to the methods specified in interface E - note that the method would be called on/passed to D's supertype, B as D does not override B's implementation of Test1()).
B b = (B)e; -> now you're casting e, which is still an instance of class D (see first instantiation) to type B. This is possible because class D extends class B therefore class B is a supertype of class D.
if you want more then my somewhat poor explanation just google search java polymorphism.
they aren't mandatory, just as none of the other object instantiations in the main method are "mandatory". In the given situation, they are just there to provide examples of polymorphism. They aren't mandatory unless you need an instance of whatever classes are being instantiated. (e.g., the cast to (E) isn't necessary unless you need access to methods defined by the interface E - note that the object you want to cast to E must implement interface E or have a super class that implements E).