0

I'm new to Java and confused with static binding. Some sites explain method overloading is static binding. My understanding is only Static, Final and Private methods are bind statically. In below example, I think print method (two overloaded print methods in SuperClass) is bind dynamically not statically because sub class print method can override the super class print method during run time. Is only Static, Final and Private methods are bind statically and the rest (public, protected ...) are dynamically bind ? Please correct me.

import java.util.Collection;
import java.util.HashSet;

public class Binding
    {
    public static void main(String[] args)
        {
        Collection<String> col = new HashSet<>();
        col.add("hello");
        SuperClass sdObj1 = new SuperClass();
        sdObj1.print(col);
        SuperClass sdObj2 = new SubClass();
        sdObj2.print(col);
        }
    }

class SuperClass
    {
    void print(Collection<String> col)
        {
        System.out.println("SuperClass1");
        }

    void print(HashSet<String> hs)
        {
        System.out.println("SuperClass2");
        }
    }

class SubClass extends SuperClass
    {
    void print(Collection<String> col)
        {
        System.out.println("SubClass");
        }
    }
j321123j
  • 21
  • 1
  • 4
  • 1
    Related: https://stackoverflow.com/questions/29381292/method-binding-in-java – Hulk Dec 02 '20 at 07:52
  • So basically, yes. Overload resolution first statically decides which method to pick, but the overridden method executed at runtime is determined based on the runtime type of the object method is invoked on. – Hulk Dec 02 '20 at 08:01

0 Answers0