questions for dynamic binding and signature method in java ab

119 views Asked by At

Matching a method signature and binding a method implementation are two sepearate issue so ,what's wrong with the follows code?

Container c5 = new JButton();

Object c6 = new JButton();

c5.add(c6);       //----it is wrong,why?

for me , c5 is a reference variable which contain reference to object of JButton,and JButton extends the class Component,so it should be right so why ?

1

There are 1 answers

1
markspace On

Java is a Single-Dispatch language. That means its method signature analysis is done at compile time, not run time.

The type of c6 is Object. (Yes, you assign a JButton, but the declared type of the variable is still Object.) So when Java looks at c5 (a Container) and its methods, it doesn't see an add() method that takes an Object. So it flags it as an error.