Search code examples
javadynamic-bindinglate-static-binding

Static binding and dynamic binding with no methods


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.


Solution

  • "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.