1

I had an exam in my college on objected-oriented programming. One of the questions was about static binding and dynamic Binding.

The question was as follows:

Shape s; if(i==1) s = new Point(1,2); else s = new Rectange(10,20); //this is dynamic binding.

YES/NO enter image description here it's not my answer btw.

My teacher said the answer is "no" because it's static binding.

As I know static binding and dynamic binding happen only when I call methods. I read all the StackOverflow questions and a lot of blog posts about this topic and the only answer I can come up with is that there is dynamic binding.

Any explanation will be appreciated.

humazed
  • 74,687
  • 32
  • 99
  • 138
  • 1
    You hardcoded that `s` refers either to a `Point` or to a `Rectangle` instance ... what is _dynamic_ about that? – Tom Dec 28 '15 at 18:07
  • 1
    This is only a guess, but maybe what your teacher meant is that the possible types are known at compile time. There's no way to introduce a new, unknown type at runtime, as there would be if you used reflection to instantiate an object. – erickson Dec 28 '15 at 18:08

2 Answers2

3

"binding" just means you're associating a name with an object, so there is binding going on here.

This is dynamic binding, see the wikipedia article:

The binding of names before the program is run is called static (also "early"); bindings performed as the program runs are dynamic (also "late" or "virtual").

An example of a static binding is a direct C function call: the function referenced by the identifier cannot change at runtime.

But an example of dynamic binding is dynamic dispatch, as in a C++ virtual method call. Since the specific type of a polymorphic object is not known before runtime (in general), the executed function is dynamically bound.

Even though the posted code predetermines what s gets set to by setting i, what makes this dynamic is that methods called on s will get resolved at runtime.

Community
  • 1
  • 1
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
1

No. It's dynamic binding.

The value of i variable is not known at compile time. Depending on value of i variable at run time, Shape has been set. As Nathan Hughes suggested, the methods called on Shape are resolved at runtime, which makes it late dynamic binding.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211