- Static and Dynamic Binding in Java
- 1. Introduction
- 2. Understanding Through a Code
- 3. Conclusion
- Static and dynamic binding in java
- What is reference and object?
- Static and Dynamic Binding in Java
- Static Binding or Early Binding
- Static binding example
- Dynamic Binding or Late Binding
- Dynamic binding example
- Static Binding vs Dynamic Binding
- Top Related Articles:
- About the Author
- Comments
Static and Dynamic Binding in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Introduction
Polymorphism allows an object to take multiple forms – when a method exhibits polymorphism, the compiler has to map the name of the method to the final implementation.
If it’s mapped at compile time, it’s a static or early binding.
If it’s resolved at runtime, it’s known as dynamic or late binding.
2. Understanding Through a Code
When a subclass extends a superclass, it can re-implement methods defined in by it. This is called a method overriding.
For example, let’s create a superclass Animal:
public class Animal < static Logger logger = LoggerFactory.getLogger(Animal.class); public void makeNoise() < logger.info("generic animal noise"); >public void makeNoise(Integer repetitions) < while(repetitions != 0) < logger.info("generic animal noise countdown " + repetitions); repetitions -= 1; >> >
public class Dog extends Animal < static Logger logger = LoggerFactory.getLogger(Dog.class); @Override public void makeNoise() < logger.info("woof woof!"); >>
On overloading a method, like the makeNoise() of Animal class, the compiler will resolve the method and its code at compile time. This is an example of static binding.
However, if we assign an object of type Dog to a reference of type Animal, the compiler will resolve the function-code mapping at runtime. This is dynamic binding.
To understand how this work, let’s write a small code snippet to call the classes and its methods:
Animal animal = new Animal(); // calling methods of animal object animal.makeNoise(); animal.makeNoise(3); // assigning a dog object to reference of type Animal Animal dogAnimal = new Dog(); dogAnimal.makeNoise(); The output of the above code will be:
com.baeldung.binding.Animal - generic animal noise com.baeldung.binding.Animal - generic animal noise countdown 3 com.baeldung.binding.Animal - generic animal noise countdown 2 com.baeldung.binding.Animal - generic animal noise countdown 1 com.baeldung.binding.Dog - woof woof!
class AnimalActivity < public static void eat(Animal animal) < System.out.println("Animal is eating"); >public static void eat(Dog dog) < System.out.println("Dog is eating"); >>
Let us add these the line to the main class:
AnimalActivity.eat(dogAnimal);
com.baeldung.binding.AnimalActivity - Animal is eating
This example shows that a static function undergoes static binding.
The reason is that subclasses cannot override static methods. If the subclass implemented the same method, it would hide the method of the superclass. Similarly, if a method is final or private, the JVM will do a static binding.
A static bound method isn’t associated with a particular object but rather is called on Type (class in Java). Execution of such a method is marginally faster.
Any other method is automatically a virtual method in Java by default. The JVM resolves such methods at runtime and this is dynamic binding.
The exact implementation depends on the JVM, but it would take a C++ like approach, where the JVM looks up the virtual table to decide on which object the method would be called.
3. Conclusion
Binding is an integral part of a language that implements polymorphism, it’s important to understand the implications of both static and dynamic binding to be sure that our applications are behaving as we want them to.
With that understanding, however, we are able to effectively use class inheritance as well as method overloading.
As always, the code is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Static and dynamic binding in java
Association of method call to the method body is known as binding. There are two types of binding: Static Binding that happens at compile time and Dynamic Binding that happens at runtime. Before I explain static and dynamic binding in java, lets see few terms that will help you understand this concept better.
What is reference and object?
class Human < . >class Boy extends Human < public static void main( String args[]) < /*This statement simply creates an object of class *Boy and assigns a reference of Boy to it*/ Boy obj1 = new Boy(); /* Since Boy extends Human class. The object creation * can be done in this way. Parent class reference * can have child class reference assigned to it */ Human obj2 = new Boy(); >>
Static and Dynamic Binding in Java
As mentioned above, association of method definition to the method call is known as binding. There are two types of binding: Static binding and dynamic binding. Lets discuss them.
Static Binding or Early Binding
The binding which can be resolved at compile time by compiler is known as static or early binding. The binding of static, private and final methods is compile-time. Why? The reason is that the these method cannot be overridden and the type of the class is determined at the compile time. Lets see an example to understand this:
Static binding example
Here we have two classes Human and Boy. Both the classes have same method walk() but the method is static, which means it cannot be overriden so even though I have used the object of Boy class while creating object obj, the parent class method is called by it. Because the reference is of Human type (parent class). So whenever a binding of static, private and final methods happen, type of the class is determined by the compiler at compile time and the binding happens then and there.
class Human < public static void walk() < System.out.println("Human walks"); >> class Boy extends Human < public static void walk()< System.out.println("Boy walks"); >public static void main( String args[]) < /* Reference is of Human type and object is * Boy type */ Human obj = new Boy(); /* Reference is of HUman type and object is * of Human type. */ Human obj2 = new Human(); obj.walk(); obj2.walk(); >>
Dynamic Binding or Late Binding
When compiler is not able to resolve the call/binding at compile time, such binding is known as Dynamic or late Binding. Method Overriding is a perfect example of dynamic binding as in overriding both parent and child classes have same method and in this case the type of the object determines which method is to be executed. The type of object is determined at the run time so this is known as dynamic binding.
Dynamic binding example
This is the same example that we have seen above. The only difference here is that in this example, overriding is actually happening since these methods are not static, private and final. In case of overriding the call to the overriden method is determined at runtime by the type of object thus late binding happens. Lets see an example to understand this:
class Human < //Overridden Method public void walk() < System.out.println("Human walks"); >> class Demo extends Human < //Overriding Method public void walk()< System.out.println("Boy walks"); >public static void main( String args[]) < /* Reference is of Human type and object is * Boy type */ Human obj = new Demo(); /* Reference is of HUman type and object is * of Human type. */ Human obj2 = new Human(); obj.walk(); obj2.walk(); >>
As you can see that the output is different than what we saw in the static binding example, because in this case while creation of object obj the type of the object is determined as a Boy type so method of Boy class is called. Remember the type of the object is determined at the runtime.
Static Binding vs Dynamic Binding
Lets discuss the difference between static and dynamic binding in Java.
- Static binding happens at compile-time while dynamic binding happens at runtime.
- Binding of private, static and final methods always happen at compile time since these methods cannot be overridden. When the method overriding is actually happening and the reference of parent type is assigned to the object of child class type then such binding is resolved during runtime.
- The binding of overloaded methods is static and the binding of overridden methods is dynamic.
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
I was searching for static vs dynamic binding and found this, very helpful for me. Thank you so much for explaining these concepts with examples
I am glad that you liked it. let me know if you have any question regarding binding in java, I would be happy to help you out.
I understood the above points about early and late binding, however can you please explain binding in terms of references? It would be really helpful for me.
Harry – let me explain your doubt with the help of few examples –
Static binding:
it means that the references are resolved during compile time by compiler
lets say – Car obj = new Car();
obj.drive(); Compiler won’t face any difficulty while resolving the conflict during compilation. Dynamic Binding:
Another example – public void myMethod(Object obj) ((Car)obj).drive();
>
In this case compiler can’t resolve the object reference during compilation. Hence this can be resolved during run time only. This is called dynamic binding.
Iamnot clear with the explaination actually do you mean dynamic polymorphism and dynamic binding are same
Hi Chaitanya, as you say in dynamic binding that, compiler gets confused while choosing method either from parent class or from child class. But how does it make right choice?
Hi Akshay, References can only be resolved at runtime. Lets take the above example to understand this:
The fact that myobj is refers to the object of its child class Boy is resolved at runtime only. Hence, at compile time the compiler can’t be sure if the call to the method ‘walk()’ on these references actually refer to which version of the method – the super class version or the sub class version. That’s the reason such type of binding happens at runtime and known as dynamic binding.
If the references variables are resolved at runtime then what will you call this below: A ob = new ob():
ob.Show(); so here there is nothing ambiguous, so what should we call it early or late binding?
hi Chaitanya , your tutorial was very nice. Thank you so much for woderful explanation with examples.