Program1:Overriden Method Rename
Example of :Overriden Method Rename
//List is a base class
class List{
void m(){
f1(); //before the instance f(), if we rename it to f1()
}
void f1(){
System.out.println("List::f()");
}
}
//child class stack , it doesn,t have f1() method , f1() is not overriden
class Stack extends List{
void f(){
System.out.println("Stack::f()");
}
}
public class Main{
public static void main(String[] args) {
//List l = new List();
//l.m();-----> output is List::f()
//Stack s = new Stack();
//s.m();-----> output is stack::f()
List l1 = new List();
List l2 = new Stack();
l1.m(); ------->output is List::f()
l2.m();------>output is stack::f()
}
}////After rename f() to f1() out put is List::f()
List::f()
After rename f() to f1() output is List::f(), List::f() — is this correct?
Yes, that is correct — because f1() is not overridden in Stack.
Let me know if you want to see a version of the code with the output printed for both versions (f() and f1()) side-by-side.
Now Stack overrides f(), and dynamic dispatch will apply:
-------------------------------------------------------------------------------------------------
Key Concepts:
-
List.m()callsf1()-
f1()is defined only inList. -
f1()is not overridden inStack. -
Therefore, even if
List l2 = new Stack();, callingl2.m()still invokesList.m(), which callsList.f1().
-
-
Stackdefinesf(), notf1()-
So there's no method overriding of
f1()inStack.
-
-
Polymorphism doesn't apply here
-
Because
f1()is not overridden, dynamic dispatch doesn’t occur for that method call. -
So
l2.m()will still useList'sf1().
-
Confusion Clarified:
You mentioned:
//Stack s = new Stack();
//s.m();-----> output is stack::f()
This is incorrect.
Since m() calls f1() (not f()), and Stack does not override f1(), it will call List's version of f1().
No comments:
Post a Comment