Reputation: 13651
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.
Upvotes: 0
Views: 198
Reputation: 597114
Object
class does not have them()
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.
Upvotes: 7