Casting Objects
Hi All,
Say I have abstract class named A and class B that extends A.
class b = new B();
A a = (A)b;
What happens now?
after all abstract class can not be instantiated. so where doeas a refer to?
Thank u in advance
Eyal
Hi All,
Say I have abstract class named A and class B that extends A.
class b = new B();
A a = (A)b;
What happens now?
after all abstract class can not be instantiated. so where doeas a refer to?
Thank u in advance
Eyal
Here you don't need casting in such case,,
check this code
public abstract class A {
public A() {
}
public void method(){
System.out.println("Class A");
}
}
public class B extends A{
public B() {
}
public void method(){
System.out.println("Class B");
}
}
public class Test {
public Test() {
}
public static void main(String[] args) {
B b = new B();
A a = b;
a.method();
}
}
the output here would be Class B
if you want the output to be Class A
then Class B should be the next:
public class B extends A{
public B() {
}
public void method(){
super.method();
}
}
and by this way you reach Class A..
hope it helps... (^_^);
> What happens now?
> after all abstract class can not be instantiated.
Doesn't matter.
> where doeas a refer to?
It refers to an A. There's only one object. (By the way, we cast references, not objects). That object IS-A B an IS-AN A. By having an A reference to that object rather than a B reference, we're just telling the compiler "treat this as an A." So you'll only have available members that are defined on A. If B adds a method, you won't be able to call it through the A reference.