[461] in java-interest
Resolution of static methods accessed via instances
daemon@ATHENA.MIT.EDU (Doug Lea)
Fri Jun 23 10:14:30 1995
Date: Fri, 23 Jun 1995 09:44:13 -0400
From: Doug Lea <dl@altair.cs.oswego.edu>
To: java-interest@java.sun.com
The Java spec (section 5) says:
Both static variables and static methods are accessed using the class
name. For convenience, they can also be accessed using an instance of
the class.
While I guess the second statement isn't quite wrong, it is deceptive.
Accesses of statics using instances are not dynamically resolved.
Instead, the nominal types of the associated references are used.
To illustrate, here's variant of an example posted on this list last
month or so:
class ClsA {
static void printClassName() { System.out.println("ClsA"); }
ClsA() {}
}
class ClsB extends ClsA {
static void printClassName() { System.out.println("ClsB"); }
ClsB() {}
}
class Tester {
public static void main(String args[]) {
ClsB b = new ClsB();
System.out.print("b.getClass().getName():");
System.out.println(b.getClass().getName());
System.out.print("b.printClassName(): ");
b.printClassName();
ClsA a = b; // a has nominal type ClsA, actual type ClsB
System.out.print("a.getClass().getName():");
System.out.println(a.getClass().getName());
System.out.print("a.printClassName(): ");
a.printClassName();
}
}
This results in
% java Tester
b.getClass().getName():ClsB
b.printClassName(): ClsB
a.getClass().getName():ClsB
a.printClassName(): ClsA
I'm puzzled by this language design choice. It seems overly
error-prone to have the function that gets invoked to be tied to the
calling context in such an indirect fashion. Also, by providing two
syntaxes for calling static methods directly, it leaves programmers
without a syntax to call the version of an overloaded static method
most closely associated with an object's immediate class unless they
happen to know exactly which class it was defined in.
Is there a rationale for keeping resoultion static despite these problems?
(Note that with dynamic resolution, the story about this would be simpler.
Usage of the form:
obj.aStaticMethod()
would be taken as the only way to express the otherwise unsupported form:
obj.getClass().aStaticMethod()
i.e., the runtime-resolved version of class-based prefixing of static methods.)
--
Doug Lea | dl@cs.oswego.edu | dl@cat.syr.edu | 315-341-2688 | FAX 315-341-5424
Computer Science Dept, SUNY Oswego, Oswego, NY 13126 | http://g.oswego.edu/dl/
Also: Software Eng. Lab, NY CASE Center, Syracuse Univ, Syracuse NY 13244
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com