Ive saw the next paragraph in some computer science test and i'll hope i can get here a good explanation of what it means because i googled it for an hour and can't find anything..
"When we say Java language has virtual method calling we mean that in java applications the executed method is determined by the object type in run time"
What does it mean? can anyone explain it better?
Virtual function in Java is expected to be defined in the derived class. We can call the virtual function by referring to the object of the derived class using the reference or pointer of the base class. Every non-static method in Java is by default a virtual method.
A virtual function or virtual method in an OOP language is a function or method used to override the behavior of the function in an inherited class with the same signature to achieve the polymorphism.
Virtual functions allow a program to call methods that don't necessarily even exist at the moment the code is compiled. In C++, virtual methods are declared by prepending the virtual keyword to the function's declaration in the base class.
What Does Virtual Method Mean? A virtual method is a declared class method that allows overriding by a method with the same derived class signature. Virtual methods are tools used to implement the polymorphism feature of an object-oriented language, such as C#.
The author of these lines used the c++ terminology of virtual
.
A better terminology is dynamic binding / dynamic dispatch.
That means, that the object's dynamic type is "chosing" which method will be invoked, and not the static type.
For example: [pseudo code]:
class A {
public void foo() { }
}
class B extends A {
public void foo() { }
}
when invoking:
A obj = new B();
obj.foo();
B.foo()
will be invoked, and NOT A.foo()
, since the dynamic type of obj
is B
.
we mean that in java applications the executed method is determined by the object type in run time
interface Animal{
public void eat();
}
class Person implements Animal{
public void eat(){ System.out.println("Eating Food");}
}
class Eagle implements Animal{
public void eat(){ System.out.println("Eating Snake");}
}
in main
Animal animal = new Person();
animal.eat(); //it will print eating food
animal = new Eagle();
animal.eat(); //it will print eating snake
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With