HI,
class A {
//some code
}
class B extends A
{
//some code
}
class Demo
{
public static void main (String args[])
{
A a = new B();// object will create ....any explanation???
//but
B b = new A(); //will not work why??
Printable View
HI,
class A {
//some code
}
class B extends A
{
//some code
}
class Demo
{
public static void main (String args[])
{
A a = new B();// object will create ....any explanation???
//but
B b = new A(); //will not work why??
What did the compiler error message say?
B can have methods etc that are not in A.
Then b.aMethodInOnlyB() would fail.
Welcome, please use [code][/code] tags when posting code. Also, please provide a question, not just a code dump :)
Edit: Sorry, I didn't see your questions in the comments at first glance!
Hi,
A a = new B(); is acceptable during compilation because B is the subclass of A. This mean B always consist of the methods in A.
B b = new A(); is not acceptable during compilation because A "may not have" relationship with B. A may not consist the methods in B.
It will return you Type mismatch during compilation time.
You could solve the compilation error by putting in casting, where now B b = (B)new A();
However, during run-time, system return you class cast exception as A
1) not inherit from B.
2) not equal to B.
Thanks
Jing-yi