Static and Dynamic Binding in Java – A Comprehensive Guide

Updated on October 16, 2024

Article Outline

In Java, C++, and Python, object oriented programming languages, highlight the concept of static binding and dynamic binding. Methods are declared with program execution, and how methods are associated with method calls during program execution is dictated by them. The static binding happens at compile time, when the callers are bound by the type of the reference (or pointer) variable, whereas the dynamic binding happens at run time having the ability to invoke the called method based on what the object is. In this blog I will explore these concepts, what they are, how they are different, as well as see them in practice by way of practical examples of how they are used in software development.

Understanding Reference and Object

Here is the first concept that comes to me to understand the process of binding in programming is reference and object. Object oriented programming (OOP) uses these terms in that they describe how the instances of classes are created, accessed, and manipulated.

 

  • Object: What every object class would be an instance of that occupies memory space and has its own state and behaviour. It is the representation of a real world entity or concept represented with code. In an example where I have a class called Car, your object of that class will be a specific car like a “Toyota Corolla” and its attributes (state) will be colour and speed and behaviours (methods) will be accelerating or braking.

 

  • Reference: A reference is a pointer/address to the location of an object in memory. What happens when you create an object is that the reference variable stores the address of that object in order for you to work on it with your code. For example, in Java, if we write Car myCar = new Car; myCar is a reference variable which is a pointer to the object created in memory.

Importance of References and Objects in Binding

Understanding references and objects is critical for grasping how binding works:

 

  • Static binding determines the method to be called at compile time based on what kind of reference is used.
  • In dynamic binding, the method is determined at runtime, which is based on what object reference points to.
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Binding in Java

Now that binding is not new to any of us, let me quickly drop a brief concept of it before we get into static binding and dynamic binding. Binding in Java means linking a method call to its corresponding method implementation. All it means is which method implementation is classed when a method is called is decided by binding. This can either be binding at runtime or at compile time.

 

Binding and polymorphism are closely related in Java — objects of different classes are bound to appear to be members of a certain class. Polymorphism can both be implemented by inheritance and method overriding, i.e. a subclass can provide a different implementation of a method already defined in it’s superclass. It is the type of reference variable that’s used to invoke the function that determines whether static or dynamic binding is used.

Types of Binding in Java

In java, there are generally two types of binding and they are:

 

  • Static Binding
  • Dynamic Binding

Static Binding

Early binding (in static binding) can also be called static binding. In static binding, the method call is resolved at compile time as the method to be executed and the corresponding implementation is decided at compile time itself. The type of reference variable it refers to determines if it is performed or not. It is mainly in cases when the method is present in the class and is not overridden in subclass.

 

This is also referred to as static binding, or early binding. In static binding, the method has been resolved during the process of compile time. Type of reference variable, not the object to which it refers, determines whether the binding is done. We used it when: the method in which class defined and the method not overridden in subclass.

 

Also Read: Java Tutorial for Beginners

Example of Static Binding in Java

In this section, we will see an example of static binding with code implementation and an example.

class Vehicle { void start() { System.out.println("Starting Vehicle"); } } class Car extends Vehicle { void start() { System.out.println("Starting Car"); } void honk() { System.out.println("Honking Car Horn"); } } class Test { public static void main(String[] args) { Vehicle v1 = new Vehicle(); Vehicle v2 = new Car(); Car c = new Car(); v1.start(); v2.start(); c.honk(); } }

Output:

Starting Vehicle Starting Car Honking Car Horn

Explanation of the Above Example

In the above example, we look at a child class ‘Car’ which extends the parent class ‘Vehicle’. The Vehicle class has the start() method, and the Car class too has the start() method. But the Vehicle class uses the console.log(“Starting Vehicle”); print while the Car class Also, Car class has a honk() method which prints a ‘Honking Car Horn’ in the console.

 

In the main method, we create three objects: v1 of type Vehicle and v2 and c of type Car.

 

Here we are calling v1, when we do that it prints “Starting Vehicle” to the console. If we use v2 to invoke the start() method, we get “Starting Car.” It is because reference variable v2 is of type Vehicle but it points to an object of type Car. The object type determines the method that gets invoked at runtime. Now, when we execute honk() by c, then it will print “Honking Car Horn” to the console.

Dynamic Binding

Dynamic binding, or late binding, or runtime polymorphism. Dynamic binding is when the method call will be resolved at runtime meaning the method to be executed will be decided at run time. It is this binding, which is done based on the type of object it references, rather than the type of reference variable. The method is overridden in the subclass, and that is why it is usually used. In case of object type this is resolved.

Example of Dynamic Binding in Java

Now we will see an example of dynamic binding with proper code and explanation.

class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } void fetch() { System.out.println("Dog is fetching the ball"); } } public class Test { static void makeSound(Animal a) { a.sound(); } public static void main(String[] args) { Animal a1 = new Animal(); Animal a2 = new Dog(); Dog d = new Dog(); makeSound(a1); makeSound(a2); d.fetch(); } }

Output:

Animal makes sound Dog barks Dog is fetching the ball

Explanation of the Above Code

So in this case we’ve a parent class named Animal and a child class named Dog. Since the first example is in the Animal class and the second one is in the Dog class, the sound method in the Animal class is printing “Animal makes sound”) and the sound method in the Dog class is printing “Dog barks.” Also a fetch method in Dog would print “Dog is fetching the ball” to the console.

 

We have also written a static method makeSound() that accepts an argument of type Animal. The sound() method here returns the value of this Animal reference variable.

 

In the main method, we create three objects: We have a1 of Animal type, a2 of Dog type and d of Dog type. We use a1 and a2 to call the makeSound() method. To call it we use a1 and it prints “Animal makes sound” to the console. Using a2 on it, it will print Dog barks to the console. This is because when the sound() method is called based on the actual object type for a1 it gives an object of type Animal and for a2 gives an object of type Dog. For instance, when we call the fetch() end point on d, we get “Dog is fetching the ball” printed to the console.

 

Also Read: Java Interview Questions and Answers

Difference between Static Binding and Dynamic Binding

Aspect Static Binding (Early Binding) Dynamic Binding (Late Binding)
Binding Time Occurs at compile-time. The method call is linked to the method definition before the program runs. Occurs at runtime. The method call is resolved when the program is running, depending on the object type.
Method Type Associated with static methods, private methods, or final methods. These methods cannot be overridden, so they are bound early. Associated with overridden methods, typically in object-oriented programming (OOP). It allows polymorphism, where a method call is bound to the actual object type at runtime.
Performance Faster execution since the binding is resolved during compilation, resulting in quicker method lookups. Slower execution because the binding happens at runtime, requiring the program to check the object type before invoking the method.
Flexibility Less flexible, as method resolution is fixed at compile-time. It does not support runtime decision-making or polymorphism. More flexible, supporting polymorphism. It allows different objects to respond differently to the same method call based on their runtime types.
Memory Usage Generally uses less memory, as all method references are fixed during compilation. May use more memory, as the system needs to store information about the object’s runtime type for method resolution.
Example Method Overloading: The compiler determines which method to call based on the method signature (number and type of parameters). Method Overriding: The actual method that gets called is determine by the object type at runtime, not the reference type.

Conclusion

Finally, a Java developer attempting to write efficient, adaptable and maintainable code needs to have a solid understanding of Java’s static binding and its dynamic binding as illustrated in our example. Compile time resolution of the run time bindings (static binding) improves performance, while all runtime mobility (dynamic) allows polymorphic capability and facilitates flexibility. Therefore, it is vital to find the right balance between these two binding mechanisms in order to design durable and large Java applications. Understanding which locks are present, when locks occur, and what overall lock allocation is, can help developers make informed decisions to optimise code execution and build software that can accommodate the needs that a wide and ever changing range of environments demand. Want to explore Java in detail? Enrol in Hero Vired’s Certificate Program in Application Development.

FAQs
In static binding, where function calls are resolved at compile time, the caller’s code is chopped up, and the names of the function calls resolve to function bodies that the compiler embeds into the caller’s program. All static and private functions/methods of a class are bound at compile time. Dynamic binding occurs in such a way that function calls are being resolved at runtime. Because of the dynamic/late binding in OOP, function overriding is possible.
An example of dynamic binding is polymorphism, when the method implementation is determined at run time based on actual object type.
A virtual method is a method that will resolve at runtime depending on the actual object type.
It is also called dynamic binding (or late binding or runtime binding). If that is the meaning then it means code that executes a method, or an operator is decided at run time. It permits the same method or operator to behave differently in different types of objects that invoke it or interact with it.
Dynamic means energetically or forceful, and static means stationary. The use of dynamic, though, for computers means 'able to do,' whereas static means 'fixed.'

Updated on October 16, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved