• Post Reply Bookmark Topic Watch Topic
  • New Topic

Inheritance and overloading  RSS feed

 
Steve Ford
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have been going through Dan Chisholm's site preparing for the SCJP exam, and these two questions have got me stumped. Any help would be appreciated.
Quest. 1
class E {
void printS1(){System.out.print("E.printS1 ");}
static void printS2() {System.out.print("E.printS2");}
}
class F extends E {
void printS1(){System.out.print("F.printS1 ");}
static void printS2() {System.out.print("F.printS2");}
public static void main (String args[]) {
E x = new F(); x.printS1(); x.printS2();
}}
What is the result of attempting to compile and run this program?
Answer: Prints "F.printS1 E.printS2"
This makes sense to me because an instance method (ie. printS1) is choosen based on the runtime type of the object, and static methods are invoked based on the reference type of the variable. Where I get confused is in combination with this next question.
Quest 2.
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);
}}
What is the result of attempting to compile and run the program?
Answer: Prints "A"
The reasoning behind this is that variable c1 is of type A and therefore the only method that can be called using this variable is m1(A). BUT doesn't this seem to contradict the reasoning of the previous question, where the method which is invoked is based on the runtime type of the object for instance methods - and obviously m1 is an instance method. Obviously I am missing something. Any help is appreciated. Thanks in advance.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Steve,
Welcome to JavaRanch!
Java chooses among overridden methods at runtime, based on the runtime type of an object. Overridden methods are defined in different classes, related by inheritance, and always have the exact same name and argument list.
Java chooses among overloaded methods at compile time, based only on the compile-time type of a variable. Overloaded methods have the same name but different argument lists; you can have overloaded methods within a single class. The m1 methods are overloads; only one of them is visible to the compiler (the one in "A") so that's the one that's chosen.
[ April 19, 2004: Message edited by: Ernest Friedman-Hill ]
 
Steve Ford
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you,
Makes perfect sense.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!