Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading doubt?

 
Amit Parnerkar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone help me here?
class A {void m1(A a) {System.out.print("A");}}
class B extends A {void m1(B b) {System.out.print("B");}}
class C extends B {void m1(C c) {System.out.print("C");}}
class D {
public static void main(String[] args) {
A c1 = new C(); C c2 = new C(); c1.m1(c2);
}}
The output will be "A". I understand that method m1() is being overloaded here and not inherited, hence c1.m1(c2) will invoke class A's m1() method. Just wondering if I am thinking in right direction or missing something here?
 
Lionel Orellana
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that method m1() is being overloaded here and not inherited

Amit, you're right about m1 being overloaded but it is being inherited too. Class C actually has the two methods it inherits from B and C and the method of its own.
The reason the method in A is the one invoked is because you have a reference of type A. It doesn't matter what the actual type of the object at runtime is. What you need to remember is this: when choosing among OVERLOADED methods check the type of the reference, when choosing among OVERRIDEN methods use the actual type of the object.
Cheers
 
Alangudi Balaji Navaneethan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lionel what you said is correct. But I am still confusing about how you diffentiate overloading and overriding methods.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amit, take a look at marcus Green's tutorial at jchq.net
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic