nus-cs2030 / 2122-s2

CS2030 repository and wiki for AY 2021/2022 Sem 2
MIT License
0 stars 0 forks source link

Static Binding and Dynamic Binding #16

Open Geraldworks opened 2 years ago

Geraldworks commented 2 years ago

Description

Hi everyone!

I have been reading up on Static and Dynamic binding and I might have made a couple of misconceptions. Would it be appropriate to say that method overriding is essentially dynamic binding taking place because you are giving the method a new definition while running the programme? In that regard, would method overloading thus be an aspect of static binding? If that is the case how would new function definitions be stored in byte code for the same method name? It just doesn't seem to make sense how a function can take on so many abilities..?

Thanks for the help!

Topic:

Polymorphism

yongchein-o commented 2 years ago

Static Binding

Static binding means the compiler chooses the method based on the compile-time type.

class A {
  static void print() {
    System.out.println("This is superclass.");
  }
  static void print(String s) {
    System.out.println("This is superclass." + s);
  }
}

class B extends A {
  static void print() {
    System.out.print("This is subclass.");
  }
  static void print(int x) {
    System.out.println("This is subclass." + x);
  }
}

Let's say you run the above in jshell, this is the output:

jshell> A b = new B();
b ==> B@7cd62f43

jshell> b.print()
This is superclass.

jshell> b.print(1);
|  Error:
|  incompatible types: int cannot be converted to java.lang.String
|  b.print(1);
|          ^

jshell> b.print("Hello")
This is superclass.Hello

jshell> B b = new B()
b ==> B@53b32d7

jshell> b.print()
This is subclass.

jshell> b.print(1)
This is subclass.1

jshell> b.print("Hello");
This is superclass.Hello

As you can see when we have the variable b of type A, b.print() invokes the method in the superclass cos b is determined by the compiler at compile time to be of type A. It will "start" looking for the method in superclass A. I guess this is static binding.

Dynamic binding

Dynamic is just the compiler choosing which method to invoke based on the run time type of the target. I guess it will start looking for a matching method signature in the subclass first then work its way up.

I removed the static modifier:

jshell> b.print() This is subclass.

Sorry for the various update. I think I was quite confused too. Maybe this might not be the best example. Hopefully prof can clarify.