views:

61

answers:

1

Hi, I have a question regarding type conversion in Java as follows:

suppose I have a class:

class A { public void m() }

Now I do:

A a1 = new A();     // (1) 
a1.m();             // (2) 
Object o = new A(); // (3) 
o.m();              // (4) 

We can say line (1) as: a1 contains the memory address of the new object A() (created in Heap). So line (2) is definitely ok.

We can also say line (3) as: o contains the memory address of the new object A() (also, created in Heap). But line (4) obviously cannot be compiled because the Object class does not have the m() method.

But why a1 contains the address of object A(), and it "can see" the m() method; while o also contains the address of object A(), but it "cannot see" the m() method?

Is there any other explanation? (Except the reason that Object class does not have the m() method).

Thanks all.

+7  A: 

Object class does not have the m() method

That is the explanation. These things are verified at compile-time. Imagine the following:

Object o1 = new A();
Object o2 = new String();

void doSomething(Object o) {
    o.m(); // compilation error
}

Now, A has m(), but String does not. And this is indicated by a compilation error. If Java was not statically typed, this error would appear at run-time. And it is considered that the earlier the problem is discovered, the better.

Bozho
Thanks a lot for your answer. I have one more. If I write ((A)o).m()--> this is perfectly ok. So, I am not sure what actually the casting ((A)o) does (what happen in the memory) so that at compiling time, m() can be seen?
ipkiss
@ipkiss - nothing happens in memory. Casting has a little overhead for the CPU, because the runtime has to decide whether to object can be cast, or an exception is to be thrown
Bozho