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

[269 byte] By [Eyal2007a] at [2007-11-27 11:20:16]
# 1

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... (^_^);

QussayNajjara at 2007-7-29 14:41:40 > top of Java-index,Java Essentials,New To Java...
# 2

> 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.

jverda at 2007-7-29 14:41:40 > top of Java-index,Java Essentials,New To Java...
# 3

Note that casting changes the type of the reference, not the type of the object referred to.

CeciNEstPasUnProgrammeura at 2007-7-29 14:41:40 > top of Java-index,Java Essentials,New To Java...