[324] in java-interest
Re: confusion over which method is invoked
daemon@ATHENA.MIT.EDU (Arthur van Hoff)
Wed Jun 14 21:43:28 1995
Date: Wed, 14 Jun 1995 18:08:36 -0700
From: Arthur.Vanhoff@Eng.Sun.COM (Arthur van Hoff)
To: Steve.Drach@Eng.Sun.COM
Cc: java-interest@java.Eng.Sun.COM
Hi Steve,
> I'm a little confused about the output from the following program. It
> seems to me that since ClassA.printname is not an abstract method,
> then it should be called by the a.printname() statement in the main
> method. Instead the printname method in ClassB is called. I really
> don't understand why. The same program in C++ seems to work the way I
> expect.
>
> class ClassA {
> String name = "ClassA";
> void printname() {
> System.out.println("A: " + name);
> }
> }
>
> class ClassB extends ClassA {
> String name = "ClassB";
> void printname() {
> System.out.println("B: " + name);
> }
> }
>
> class AccessTest {
> public static void main(String argv[]) {
> ClassB b = new ClassB();
> ClassA a = b;
> a.printname();
Because printname is a virtual method, it will actually
call the printname in ClassB.
> System.out.println(a.name);
Because a.name is a reference to an instance variable and
since instance variables are not virtual, the value will
be "ClassA". Note that the instance contains two instance
variables that are both called "name". You could also type:
System.out.println(b.name);
or
System.out.println(((ClassB)a).name);
to get the other one printed.
> }
> }
Have fun,
Arthur van Hoff (avh@eng.sun.com)
http://java.sun.com/people/avh/
Sun Microsystems Inc, M/S UPAL02-301,
100 Hamilton Avenue, Palo Alto CA 94301, USA
Tel: +1 415 473 7242, Fax: +1 415 473 7104
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com