Dynamic binding concern - java

I've really tried to understand it but I couldn't. Why is it printed: Selected: method 1 two times?
I thought that it should be printed
Selected: method 1
Selected: method 2
because the real type of c2 is ClassTwo. Please see the code below.
public class ClassOne{}
public class ClassTwo extends ClassOne{}
public class Module {
public void methodModule(ClassOne c){
System.out.println("Selected: method 1");
}
public void methodModule(ClassTwo c) {
System.out.println("Selected: method 2");
}
}
public class TestModule {
public static void main(String[] args) {
Module m = new Module();
ClassOne c1 = new ClassOne();
ClassOne c2 = new ClassTwo();
m.methodModule(c1);
m.methodModule(c2);
}
}

Your example is not dynamic binding. It's Static binding you can see the example in the link
See here
In your example at compile It will be clear that which method will get executed. That's why It's Static binding.
Dynamic Binding is What decide at run time.
For Example in the given link if you see =>
at run time it will be known to the program at start() method of the Car Class will get executed.
Moreover you can also see Liskov Substitution Principle
If S and T are objects, and T is a subtype of S, then T may be used
where S is expected.

Some Key points are:
You have overloaded method methodModule
You are inheriting classOne
When you inherit, it becomes a subclass so the type will be compatible if you assign subclass to your parent.
If you don't inherit, it might throw some incompatible error.
When you call the method which is overloaded it will look for the same type and executes which prints first method twice.

You have method methodModule overloaded in your class Module.
Alough you assigned a ClassTwo object to c2 by: ClassOne c2 = new ClassTwo();, but since c2 is declared as a reference to ClassOne object, the methodModule(ClassOne c) method will be selected, when m.methodModule(c2); is executed.
See below code for Dynamic binding, which output your expected results:
Selected: method 1
Selected: method 2
In this code example, Overriding is used,which is usually related with Dynamic binding:
class ClassOne extends Module{
#Override
public void methodModule(){
System.out.println("Selected: method 1");
}
}
class ClassTwo extends Module {
#Override
public void methodModule() {
System.out.println("Selected: method 2");
}
}
class Module {
public void methodModule() {
System.out.println("Selected: module mothod");
}
}
public class TestModule {
public static void main(String[] args) {
Module c1 = new ClassOne();
Module c2 = new ClassTwo();
c1.methodModule();
c2.methodModule();
}
}

Related

Is Java method overloading is static binding? [duplicate]

I'm currently doing an assignment for one of my classes, and in it, I have to give examples, using Java syntax, of static and dynamic binding.
I understand the basic concept, that static binding happens at compile time and dynamic binding happens at runtime, but I can't figure out how they actually work specifically.
I found an example of static binding online that gives this example:
public static void callEat(Animal animal) {
System.out.println("Animal is eating");
}
public static void callEat(Dog dog) {
System.out.println("Dog is eating");
}
public static void main(String args[])
{
Animal a = new Dog();
callEat(a);
}
And that this would print "animal is eating" because the call to callEat uses static binding, but I'm unsure as to why this is considered static binding.
So far none of the sources I've seen have managed to explain this in a way that I can follow.
From Javarevisited blog post:
Here are a few important differences between static and dynamic binding:
Static binding in Java occurs during compile time while dynamic binding occurs during runtime.
private, final and static methods and variables use static binding and are bonded by compiler while virtual methods are bonded during runtime based upon runtime object.
Static binding uses Type (class in Java) information for binding while dynamic binding uses object to resolve binding.
Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Here is an example which will help you to understand both static and dynamic binding in Java.
Static Binding Example in Java
public class StaticBindingTest {
public static void main(String args[]) {
Collection c = new HashSet();
StaticBindingTest et = new StaticBindingTest();
et.sort(c);
}
//overloaded method takes Collection argument
public Collection sort(Collection c) {
System.out.println("Inside Collection sort method");
return c;
}
//another overloaded method which takes HashSet argument which is sub class
public Collection sort(HashSet hs) {
System.out.println("Inside HashSet sort method");
return hs;
}
}
Output: Inside Collection sort method
Example of Dynamic Binding in Java
public class DynamicBindingTest {
public static void main(String args[]) {
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle {
public void start() {
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle {
#Override
public void start() {
System.out.println("Inside start method of Car");
}
}
Output: Inside start method of Car
Connecting a method call to the method body is known as Binding. As Maulik said "Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding." So this code :
public class Animal {
void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
public static void main(String args[]) {
Animal a = new Dog();
a.eat(); // prints >> dog is eating...
}
#Override
void eat() {
System.out.println("dog is eating...");
}
}
Will produce the result: dog is eating... because it is using the object reference to find which method to use. If we change the above code to this:
class Animal {
static void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
public static void main(String args[]) {
Animal a = new Dog();
a.eat(); // prints >> animal is eating...
}
static void eat() {
System.out.println("dog is eating...");
}
}
It will produce : animal is eating... because it is a static method, so it is using Type (in this case Animal) to resolve which static method to call. Beside static methods private and final methods use the same approach.
Well in order to understand how static and dynamic binding actually works? or how they are identified by compiler and JVM?
Let's take below example where Mammal is a parent class which has a method speak() and Human class extends Mammal, overrides the speak() method and then again overloads it with speak(String language).
public class OverridingInternalExample {
private static class Mammal {
public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }
}
private static class Human extends Mammal {
#Override
public void speak() { System.out.println("Hello"); }
// Valid overload of speak
public void speak(String language) {
if (language.equals("Hindi")) System.out.println("Namaste");
else System.out.println("Hello");
}
#Override
public String toString() { return "Human Class"; }
}
// Code below contains the output and bytecode of the method calls
public static void main(String[] args) {
Mammal anyMammal = new Mammal();
anyMammal.speak(); // Output - ohlllalalalalalaoaoaoa
// 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
Mammal humanMammal = new Human();
humanMammal.speak(); // Output - Hello
// 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
Human human = new Human();
human.speak(); // Output - Hello
// 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V
human.speak("Hindi"); // Output - Namaste
// 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V
}
}
When we compile the above code and try to look at the bytecode using javap -verbose OverridingInternalExample, we can see that compiler generates a constant table where it assigns integer codes to every method call and byte code for the program which I have extracted and included in the program itself (see the comments below every method call)
By looking at above code we can see that the bytecodes of humanMammal.speak(), human.speak() and human.speak("Hindi") are totally different (invokevirtual #4, invokevirtual #7, invokevirtual #9) because the compiler is able to differentiate between them based on the argument list and class reference. Because all of this get resolved at compile time statically that is why Method Overloading is known as Static Polymorphism or Static Binding.
But bytecode for anyMammal.speak() and humanMammal.speak() is same (invokevirtual #4) because according to compiler both methods are called on Mammal reference.
So now the question comes if both method calls have same bytecode then how does JVM know which method to call?
Well, the answer is hidden in the bytecode itself and it is invokevirtual instruction set. JVM uses the invokevirtual instruction to invoke Java equivalent of the C++ virtual methods. In C++ if we want to override one method in another class we need to declare it as virtual, But in Java, all methods are virtual by default because we can override every method in the child class (except private, final and static methods).
In Java, every reference variable holds two hidden pointers
A pointer to a table which again holds methods of the object and a pointer to the Class object. e.g. [speak(), speak(String) Class object]
A pointer to the memory allocated on the heap for that object’s data e.g. values of instance variables.
So all object references indirectly hold a reference to a table which holds all the method references of that object. Java has borrowed this concept from C++ and this table is known as virtual table (vtable).
A vtable is an array like structure which holds virtual method names and their references on array indices. JVM creates only one vtable per class when it loads the class into memory.
So whenever JVM encounter with a invokevirtual instruction set, it checks the vtable of that class for the method reference and invokes the specific method which in our case is the method from a object not the reference.
Because all of this get resolved at runtime only and at runtime JVM gets to know which method to invoke, that is why Method Overriding is known as Dynamic Polymorphism or simply Polymorphism or Dynamic Binding.
You can read it more details on my article How Does JVM Handle Method Overloading and Overriding Internally.
The compiler only knows that the type of "a" is Animal; this happens at compile time, because of which it is called static binding (Method overloading). But if it is dynamic binding then it would call the Dog class method. Here is an example of dynamic binding.
public class DynamicBindingTest {
public static void main(String args[]) {
Animal a= new Dog(); //here Type is Animal but object will be Dog
a.eat(); //Dog's eat called because eat() is overridden method
}
}
class Animal {
public void eat() {
System.out.println("Inside eat method of Animal");
}
}
class Dog extends Animal {
#Override
public void eat() {
System.out.println("Inside eat method of Dog");
}
}
Output:
Inside eat method of Dog
There are three major differences between static and dynamic binding while designing the compilers and how variables and procedures are transferred to the runtime environment.
These differences are as follows:
Static Binding: In static binding three following problems are discussed:
Definition of a procedure
Declaration of a name(variable, etc.)
Scope of the declaration
Dynamic Binding: Three problems that come across in the dynamic binding are as following:
Activation of a procedure
Binding of a name
Lifetime of a binding
With the static method in the parent and child class: Static Binding
public class test1 {
public static void main(String args[]) {
parent pc = new child();
pc.start();
}
}
class parent {
static public void start() {
System.out.println("Inside start method of parent");
}
}
class child extends parent {
static public void start() {
System.out.println("Inside start method of child");
}
}
// Output => Inside start method of parent
Dynamic Binding :
public class test1 {
public static void main(String args[]) {
parent pc = new child();
pc.start();
}
}
class parent {
public void start() {
System.out.println("Inside start method of parent");
}
}
class child extends parent {
public void start() {
System.out.println("Inside start method of child");
}
}
// Output => Inside start method of child
All answers here are correct but i want to add something which is missing.
when you are overriding a static method, it looks like we are overriding it but actually it is not method overriding. Instead it is called method hiding. Static methods cannot be overridden in Java.
Look at below example:
class Animal {
static void eat() {
System.out.println("animal is eating...");
}
}
class Dog extends Animal {
public static void main(String args[]) {
Animal a = new Dog();
a.eat(); // prints >> animal is eating...
}
static void eat() {
System.out.println("dog is eating...");
}
}
In dynamic binding, method is called depending on the type of reference and not the type of object that the reference variable is holding
Here static bindinghappens because method hiding is not a dynamic polymorphism.
If you remove static keyword in front of eat() and make it a non static method then it will show you dynamic polymorphism and not method-hiding.
i found the below link to support my answer:
https://youtu.be/tNgZpn7AeP0
In the case of the static binding type of object determined at the compile-time whereas in
the dynamic binding type of the object is determined at the runtime.
class Dainamic{
void run2(){
System.out.println("dainamic_binding");
}
}
public class StaticDainamicBinding extends Dainamic {
void run(){
System.out.println("static_binding");
}
#Override
void run2() {
super.run2();
}
public static void main(String[] args) {
StaticDainamicBinding st_vs_dai = new StaticDainamicBinding();
st_vs_dai.run();
st_vs_dai.run2();
}
}
Because the compiler knows the binding at compile time. If you invoke a method on an interface, for example, then the compiler can't know and the binding is resolved at runtime because the actual object having a method invoked on it could possible be one of several. Therefore that is runtime or dynamic binding.
Your invocation is bound to the Animal class at compile time because you've specified the type. If you passed that variable into another method somewhere else, noone would know (apart from you because you wrote it) what actual class it would be. The only clue is the declared type of Animal.

Instantiating base class using derived class?

Here is my code, I cannot reason out why the output is coming to be like that. If anyone can explain please.
import java.io.*;
class b {
void m(b a){
System.out.println(" b");
}
}
class bcd extends b {
void m(bcd a){
System.out.println("bcd");
}
}
class cde extends bcd {
void m(cde a){
System.out.println("cde");
}
}
public class ABC{
public static void main(String[] args){
b ob1= new cde();
cde ob2=new cde();
ob1.m(ob2);
}
}
In your example will call method in class b. I think you want to show overriding or overloading example, but this is not overriding and not overloading.
For overriding use late binding. In this case, knowing the method signature, the virtual machine analyzes instantiating(real) type of object on which this method is called to determine exactly which class to take the definition of the method being called.
For overloading use earlier binding. In this case, compiler checking a formal type of object
Good example explain overriding or overloading this:
public class Test{
public static class Parent{
public void test(){
System.out.println("parent class");
}
}
public static class Child extends Parent{
public void test(){
System.out.println("child class");
}
}
public static class Tester{
public void test(Parent obj){
System.out.println("Parent method");
obj.test();
}
public void test(Child obj){
System.out.println("Child method");
obj.test();
}
}
public static void main(String[] args){
Parent obj = new Child();
Tester t = new Tester();
t.test(obj);
}
}
Result execution:
Parent method
child class
EDIT:
1)Compiler don't look on type the parameter. It determine, what method calling, based on real type object on which it was called: for your example this is b class, for my example this is Tester class.2) if we have two methods in a class with the same name, but different type parameter in the method (overloading), then java virtual machine look on the type parameter(how in my example: two methods with the same name, but transmitted the object of class Parent and calling method with Parent parameter)
In your example if was like this:
class B {
void m(B a){
System.out.println(" b");
}
void m(Cde a){
System.out.println("cde");
}
}
public class ABC{
public static void main(String[] args){
B ob1= new Cde();
Cde ob2=new Cde();
ob1.m(ob2);
}
}
It's example overloading and will call void m(cde a)
EDIT2:
Yes, your ob1 object is instance cde, but java virtual machine check instantiating(real) type of object only in case overriding(when signature of methods in two classes are identical). So, you need to remember two things overriding and overloading, in other cases compiler look on formal type reference, in your example this is b.
But there is interesting thing with overriding.
From http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.5
Return types may vary among methods that override each other if the
return types are reference types. The notion of
return-type-substitutability supports covariant returns, that is, the
specialization of the return type to a subtype.
A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2,
if and only if the following conditions hold:
If R1 is void then R2 is void.
If R1 is a primitive type, then R2 is identical to R1.
If R1 is a reference type then:
R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or
R1 = |R2|
if you have this code with different return type, but identical parameter, it will be example overriding too:
class Bcd extends B {
#Override
Bcd m(Cde a) {
System.out.println("bcd");
return a;
}
}
class Cde extends Bcd {
#Override
Cde m(Cde a) {
System.out.println("cde");
return a;
}
}
class B {
B m(Cde a) {
System.out.println("b");
return a;
}
}
class Test {
public static void main(String[] args) {
final B ob1 = new Cde();
final Cde ob2 = new Cde();
ob1.m(ob2);
}
}
Result:
cde
Because this is overriding too.
When you are calling ob1.m(ob2); then method of class b is getting invoked.
The methods defined in class
class bcd extends b {
void m(bcd a) {
System.out.println("bcd");
}
}
class cde extends bcd {
void m(cde a) {
System.out.println("cde");
}
}
are overloaded methods not overriden methods.

If a class inherits a method does calling that method on that class point to the super class or does it make a local copy within the child class?

Say I have Class A and Class B. Class B extends Class A. Class A has one method.
public class notimportant
{
public void one()
{
}
}
public class A extends notimportant
{
public void one()
{
//assume there is a super class making this call legal which doesnt do anything
super.one();
System.out.println("blah");
}
}
public class B extends A
{
}
A var1 = new B();
if I call 'var1.one();' will the output end up being:
"blah"
"blah"
because it creates a local copy of 'one()' in Class B and then reads that which calls 'super()' which leads it up to method 'one()' in Class A OR does it just print
"blah"
because it knows to look directly at Class A
EDIT: Hope that is a lot more clear now.
It will follow the way you have it currently written:
-> New object of class B
-> Call method One on this object
-> First line calls supermethod, proceed to execute it
-> Second line prints out after that
Your code doesn't compile at all though, you might want to clear that up. What's keeping you from testing this yourself?
Here's the new situation as you described it. Everything still works as expected, you just add a layer.
public class C {
public void test() {
System.out.println("Inside C");
}
}
public class B extends C {
public void test() {
super.test();
System.out.println("Inside B");
}
}
public class A extends B {
public static void main(String[] args) {
A obj = new A();
obj.test();
}
}
Output:
Inside C
Inside B
super means your superclass – it's resolved at compile-time.
It does not mean the immediate parent class of whatever the runtime type of this is.

Can a private method in super class be overridden in the sub-class?

Can private methods be overridden in Java?
If no, then how does the following code work?
class Base{
private void func(){
System.out.println("In Base Class func method !!");
};
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("In Derived Class func method");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func();
}
}
No, you are not overriding it. You can check by trying to mark it with #Override, or by trying to make a call to super.func();. Both won't work; they throw compiler errors.
Furthermore, check this out:
class Base {
private void func(){
System.out.println("In base func method");
};
public void func2() {
System.out.println("func2");
func();
}
}
class Derived extends Base {
public void func(){ // Is this an overriding method?
System.out.println("In Derived Class func method");
}
}
class InheritDemo {
public static void main(String [] args) {
Derived D = new Derived();
D.func2();
}
}
It will print:
func2
In base func method
When you change func() in Base to public, then it will be an override, and the output will change to:
func2
In Derived Class func method
No, a private method cannot be overridden because the subclass doesn't inherit its parent's private members. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class. There is no way an overriding method would be banned from accessing the method it is overriding, but this would precisely be the case here.
No, it is not. You can mark an override just to make sure like this:
#Override
public void func(){
System.out.println("In Derived Class func method");
}
And in this case it would be a compiler error.
You are not overriding. You cannot override private members, you are merely defining a new method in Derived. Derived has no knowledge Base's implementation of func() since its declared as private. You won't get a compiler error when you define func() in Derived but that is because Derived does not know Base has an implementation of func(). To be clear: it would be incorrect to say you are overriding Base's implementation of func().
In addition to the already correct answer, consider this:
public class Private {
static class A {
public void doStuff() {
System.out.println(getStuff());
}
private String getStuff() {
return "A";
}
}
static class B extends A {
public String getStuff() {
return "B";
}
}
public static void main(String[] args) {
A a = new A();
a.doStuff();
a = new B();
a.doStuff();
B b = new B();
b.doStuff();
}
}
This will print
A
A
A
although B "overrides" getStuff(). As implementation of doStuff() is fixed to calling A#getStuff(), no polymorphism will be triggered.
Nope because if you do something like Base b = new Derived(); you still won't be able to call b.func(). What you're doing is called "hiding".
Since the method is private it is not visible to the other classes.Hence the derived class does not inherit this method.
So this is not the case of overriding
Method hiding will be happening here instead of overriding. like what happens in case of static.
Actually,you are not overriding.Before Java5
an overridden method's return type must match with parent class's method.
But Java 5 introduced a new facility called covariant return type.You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
you can follow this thread :Can overridden methods differ in return type?
The private member of the base class cannot be access by anyone outside of the class and cannot be overridden. The function in the derive class is an independent function that can be access by anywhere.
The code would run the function in the derived class
A private method can never be over ridden. It is always hidden.
In your example - Derived class has one parent class private method and has its own function func. Both are different, and the func is not over ridden. Its a separate independent function.
If you create a new function in parent class calling parent class function, the parent func will be called, if parent class reference is used as opposed in the case of method over ridding
Note : An object defines the members which it has, and a reference defines which it can access
// Method Over ridding case
class Base{
public void func(){
System.out.println("Parent class");
};
public void func1(){
func();
}
}
class Derived extends Base{
public void func(){
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1(); // Prints Derived class - no matter parent reference is calling,as there as method is overridden - Check func1() is in parent class, but id doesn't call parent class func() as the compiler finds a func() method over ridden in derived class
}
}
// Method Hidding case - Private and static methods case
class Base{
private void func(){
System.out.println("Parent class");
};
public void func1(){
func()
}
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1();
// Prints Parent class - the reason is we are using the parent class reference, so compiler is looking for func() and it founds that there is one private class method which is available and is not over ridden, so it will call it. Caution - this won't happen if called using derived class reference.
b.func();
// this prints the Derived class - the compiler is looking func(), as Derived class has only one func() that it is implementing, so it will call that function.
}
}
Read comments in the below code snippet to find the answer.
Sources:
Definition reference:
Credits for the source code example(reference) from the book - "OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1Z0-808 Book" from 'Jeanne Boyarsky' and 'Scott Selikoff'.
public class Deer {
public Deer() { System.out.print("Deer"); }
public Deer(int age) { System.out.print("DeerAge"); }
private boolean hasHorns() { return false; }
public static void main(String[] args) {
Deer deer = new Reindeer(5);
System.out.println(","+deer.hasHorns());// false is printed.
}
}
class Reindeer extends Deer {
public Reindeer(int age) { System.out.print("Reindeer"); }
private boolean hasHorns() { return true; } // Overriding possible, but is of no use in the below context.
// Below code is added by me for illustration purpose
public static void main(String[] args) {
Deer deer = new Reindeer(5);
//Below line gives compilation error.
//System.out.println(","+deer.hasHorns());
}
}

Regarding static and dynamic binding in Java

Please explain the concept of static and dynamic binding in Java.
What I have grasped is that Static binding in Java occurs during compile time while dynamic binding occurs during Runtime, static binding uses Type (Class in Java) information for binding while dynamic binding uses Object to resolve binding.
This is the code for my understanding.
public class StaticBindingTest {
public static void main (String args[]) {
Collection c = new HashSet ();
StaticBindingTest et = new StaticBindingTest();
et.sort (c);
}
//overloaded method takes Collection argument
public Collection sort(Collection c) {
System.out.println ("Inside Collection sort method");
return c;
}
//another overloaded method which takes HashSet argument which is sub class
public Collection sort (HashSet hs){
System.out.println ("Inside HashSet sort method");
return hs;
}
}
and the output of the above program was inside the collection sort method
for dynamic binding...
public class DynamicBindingTest {
public static void main(String args[]) {
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle {
public void start() {
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle {
#Override
public void start() {
System.out.println ("Inside start method of Car");
}
}
the output was inside the start method of Car. Please advise: Is this understanding correct and please advise some more examples. Thanks.
Static binding is used at compile time and is usually common with overloaded methods - the sort() methods in your example where the type of the argument(s) is used at compile time to resolve the method.
Dynamic binding (dynamic dispatch) is usually associated with polymorphism and overriding methods - the start() method in your example where the type of the receiver (vehicle) is used at runtime to resolve the method.
I think you have summarized it correctly and shams also correctly added more information for you. Just to add little more information for you first let me step back by stating that the association of method definition to the method call is known as binding. So, static binding as you pointed out correctly, is the binding that can be resolved at compile time by compiler (also known as early binding or static binding). On the other hand, dynamic bidding or late binding it means compiler is not able to resolve the call/binding at compile time (it happens at the run time). See below for some examples:
//static binding example
class Human{
....
}
class Boy extends Human{
public void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
Boy obj1 = new Boy();
obj1.walk();
}
}
//Overriding is a perfect example of Dynamic binding
package beginnersbook.com;
class Human{
public void walk()
{
System.out.println("Human walks");
}
}
class Boy extends Human{
public void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
//Reference is of parent class
Human myobj = new Boy();
myobj.walk();
}
}
source

Categories

Resources