[336] in java-interest

home help back first fref pref prev next nref lref last post

Re: confusion over which method is invoked

daemon@ATHENA.MIT.EDU (David Geary)
Thu Jun 15 12:13:59 1995

Date: Thu, 15 Jun 1995 09:56:52 +0700
From: David.Geary@Central.Sun.COM (David Geary)
To: java-interest@java.Eng.Sun.COM

> > 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.

  In C++, it makes no difference whether printname() is virtual or not.
a.printname() should invoke A::printname(), since a is an object of class A.

  Unless Java has modified the assignment semantics of C++, A::printname()
should be invoked for a.printname().

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 David Geary                             "Sometimes I eulogize, I mythologize"
 geary@rmtc.Central.Sun.COM
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post