Monday, July 1, 2013

Dynamic Binding in Java

Dynamic Binding

class Father{
a(){ ... }
b(){a();}
}
class Son extends Father{
a(){ ..... }} //override

b() is not overrided. When I create an instance of Son and I call b(), Father's a() is called, but I would like it executes the Son one (if the object is a Son). Is it possible? Answers: No/Yes No: "When I create an instance of Son and I call b(), Father's a() is called," That is wrong! Yes: "but I would like it executes the Son one (if the object is a Son). Is it possible?" -- That is the behavior of Java If a is not a static method, then java use dynamic binding, so the son's a() method is called. new Son().b() will invoke the method a() in Son. That is called dynamic binding.

How to call the overridden superclass methor

no. once you've overridden a method then any invocation of that method from outside will be routed to your overridden method (except of course if its overridden again further down the inheritance chain). you can only call the super method from inside your own overridden method like so:
public String someMethod() {
   String superResult = super.someMethod(); 
   // go on from here
}
but thats not what youre looking for here. you could maybe turn your method into:
public List getNameAbbreviations() {
   //return a list with a single element 
}
and then in the subclass do this:
public List getNameAbbreviations() {
   List fromSuper = super.getNameAbbreviations();
   //add the 3 letter variant and return the list 
}

No comments:

Post a Comment