What is static and dynamic binding in Java ?

Static Binding

  • The binding which can be determined at compile time by compiler is known as static binding.
  • The binding of static, private and final methods is compile-time.
  • The class is determined at the compile time only. So, method cannot be overridden.
  • Object of local class to be accessed in static.

Sample Code

public class NewClass 
{
public static class superclass
{
static void print()
{
System.out.println("print in superclass.");
}
}
public static class subclass extends superclass
{
static void print()
{
System.out.println("print in subclass.");
}
}

public static void main(String[] args)
{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}

Output

print in superclass.
print in superclass.

Dynamic Binding

  • When compiler is not able to determination the call/binding at compile time, such binding is known as Dynamic or late Binding.
  • Method Overriding is the good example for dynamic binding.
  • In overriding concept have the both parent and child classes should be presented they have same method and in this case the type of the object only determines which method is to be executed.
  • At the run time is determined to the type of object. So, this is known as dynamic binding.

Sample Code

public class NewClass 
{
public static class superclass
{
void print()
{
System.out.println("print in superclass.");
}
}

public static class subclass extends superclass
{
@Override
void print()
{
System.out.println("print in subclass.");
}
}

public static void main(String[] args)
{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}

Output

print in superclass.
print in subclass.

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,