Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

overriding cofusion

 
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have two classes, one inheriting from another, both with two methods, parameterless and with parameters:

class A {
void m1(A a) { System.out.println("A.m1(A a)"); }
void m2() { System.out.println("A.m1()"); }
}

class B extends A {
void m1(B b) { System.out.println("B.m1(B b)"); }
void m2() { System.out.println("B.m1()");
}
}

The result of:

A b1 = new B();
B b2 = new B();
b1.m1(b2);
b1.m2();

is:

A.m1(A a)
B.m1()

Why does the absence of parameter has an influence on choosing the method's class?
Thnx a lot.
 
Michael Wiezik
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
P.S. Bear in mind the run-time class of b1 is different than it's compile-time class
 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Michal Wiezik:
You have two classes, one inheriting from another, both with two methods, parameterless and with parameters:

class A {
void m1(A a) { System.out.println("A.m1(A a)"); }
void m2() { System.out.println("A.m1()"); }
}

class B extends A {
void m1(B b) { System.out.println("B.m1(B b)"); }
void m2() { System.out.println("B.m1()");
}
}

The result of:

A b1 = new B();
B b2 = new B();
b1.m1(b2);
b1.m2();

is:

A.m1(A a)
B.m1()

Why does the absence of parameter has an influence on choosing the method's class?
Thnx a lot.



I believe the first method is overloaded, not overriden. In the case of overloaded methods, the method to call is determined at compile time. Since the reference variable is of Class A, it will call Class A's version of m1. If the method were overriden, it would have called Class B's version
[ July 23, 2004: Message edited by: Chris Allen ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic