Reputation: 53
Suppose I have a class called A
. I have another class that extends A
called B
.
B
contains a method called BsMethod()
that A
does not contain.
Say I declare an array of A
: arrA = new A[10]
And I assign arrA[1] = new B();
And I try to call BsMethod
by doing arrA[1].BsMethod()
This gives an error saying that arrA
does not contain this method. What should I change so that I can call BsMethod
using arrA[1]
?
Upvotes: 1
Views: 58
Reputation: 13402
This is failing because at the compile java compiler is not able to bind the method with class A
object, it can not find the method BsMethod()
in class A
.
You can cast the object to class B
and use it.
((B)arrA[1]).BsMethod();
In the Dynamic Binding the actual method call are determined at the run time. So if you have a method in super class and you also override it in the sub class. Then the actual method call, for such method, is determined at the runtime.
You can read more about static and dynamic binding here with example. Static Binding and Dynamic Binding
Upvotes: 2
Reputation: 1683
You have to cast arrA[1]
as B
since arrA
is an array of A
and the compiler doesn't know about B
at this point.
Call it like this: ((B)arrA[1]).BsMethod()
Upvotes: 1