Java Solaris Communities Sun Store Join SDN My Profile Why Join?
 
Bug Database
Bug Detail
Quick Lists
Top 25 Bugs
Top 25 RFE's
Recently Closed Bugs
Printable Page Printable Page


Bug Database
Bug ID: 4093687
Votes 208
Synopsis Extension of 'Interface' definition to include class (static) methods.
Category java:specification
Reported Against 1.1.4 , 1.1.5 , 1.2.2 , 1.4.1 , 1.4.2 , merlin-beta , kestrel-beta
Release Fixed
State 6-Fix Understood, request for enhancement
Priority: 4-Low
Related Bugs 4291381 , 4306573 , 4491759 , 4804452 , 5046180 , 4193604
Submit Date 18-NOV-1997
Description


Please extend the definition of an 'Interface'
to include class (static) methods.

Currently, attempting to expose class methods 
via an interface generates a compiler error, e.g.

MyInterface.java:2: Interface methods can't be 
native, static, synchronized, final, private, 
or protected : void classMethod()
    public static void classMethod ();

This limitation forces one to create two classes
and two interfaces (which in turn creates other
difficulties), instead of one of each, in order
to publish class methods e.g. 'Orders' and 'Order'
classes and interfaces.  Visual Basic's lack of 
class methods forces one to do the same thing.

Noting the other exclusions above, I would also
question why interfaces cannot have final or
synchronized methods.
(Review ID: 19893)
======================================================================
Posted Date : 2005-11-11 02:09:25.0
Work Around



======================================================================
Evaluation
The fact that interfaces cannot impose constraints on class methods is a problem. I don't know if a language change to address this will ever be realistic, but I believe it's a good idea. 

The other comments (i.e., why an interface method cannot be synchronized or final) show a misunderstanding. These properties are not part of the type of a method, but of its implementation, and interfaces have no business dictating such details.

  xxxxx@xxxxx   1997-11-18
This request is being considered for Dolphin.  However, we may well decide
not to include this in Dolphin.  If so, this RFE will be closed.
Posted Date : 2006-02-27 04:50:09.0
Comments
  
  Include a link with my name & email   

Submitted On 27-NOV-1997
Parkway
The compiler assumes all interface methods are
abstract, and abstract methods can't be declared
static, final, native or synchronized.
An interface can't impose a constraint on a
static method, because all static methods are
final and no static methods are abstract.
(But that doesn't appear to stop interfaces
defining static methods per se, it's just that
the compiler won't let you define it.)


Submitted On 15-JAN-1998
davidholmes
I think the whole purpose of interfaces needs to be re-assessed for Java 2.0
(or sooner)  given the changes that have been added to java since it first came
out.
Thinks to consider include:
 - creation of static methods
 - final non-static instance variables
 - interaction with inner classes 


Submitted On 03-APR-1998
KizubM
I'd like to vote the idea.
I've wrote a java compiler that allows non-static
fields and non-abstract methods in an interface.
Each non-static fields access is replased by
set$name() and get$name() autogenerated
methods. Each method's body is a "default"
implementation for classes that do not
implement this method explicitly.
Here is an example:
interface I {
	int field;
	int foo() { return field; }
}
class C implements I {
	virtual int field; // implementation of a field
}
will be compiled into:
interface I {
	void set$field(int value);
	int get$field();
	static int foo(I this) {
		return this.get$field();
	}
}
class C implements I {
	int field;
	void set$field(int value) {
		field = value;
	}
	int get$field() { return field; }
	int foo() { return I.foo(this); }
}
This allows to include common code for each
class that implements an interface without
code duplication.
Right now java executes generated classes
(i.e. uses static methods in interfaces -
maybe because <clinit> is the static method,
so JVM already knows how to do this),
but verifier and javac complains to
execute/compile the code.
To be verifier-compitible I need to
create a special dummy class, to say,
I_default_implementation, and call not
I.foo(this), but 
I_default_implementation.foo(I this).
I think - to allow bytecoder to pass such
interfaces (with static methods) has
more sence, and making additional classes
is a stupid idea...


Submitted On 26-JUN-1998
rubz
I think interfaces SHOULD definitely allow the definition of static methods.
They could of course be abused, but it avoids having to rewrite the same method
(e.g. sort(Object o, Object p) for every class that implements it. I don't see
it being a regularly used feature, but even so it would be a handy one to have.


Submitted On 16-JUL-1998
MartDesruisseaux
Non-abstract method would be useful in interface in order to provide default
implementation. I'm not asking for fields (which, I think, is the problem of
multiple inheritances), but only access to other methods. Example:
interface Matrix {
    Number get(int row, int col);
    double doubleValue(int row, int col) {
        return get(row,col).doubleValue();
    }
    float floatValue(int row, int col) {
        return get(row,col).floatValue()
    }
//  etc... Of course, implementations of
//         'Matrix' should provide more
//         efficients 'doubleValue' and
//         'floatValue' methods.
}
Anyway, I would like it but I think JavaSoft would probably don't. One can said
I should use a class instead. Well, since Java don't have a 'const' keyword
(unfortunately), some class have to exist in two versions: mutable and
immutable. With an hierarchy like this:
   Vector
    |
    +--------------------------+
    |                          |
   ComplexNumbersVector    MutableVector
    |                          ?
    +--------------------------+
    |                          |
   RealNumbersVector       MutableComplex...
    |                          ?
    +--------------------------+
    |                          |
   IntegerNumbersVector    MutableReal...
The only way I know to do that is to use an interface for 'Mutable' objects.
Unfortunately it force me to duplicate a lot of code, since interfaces can't
contains non-abstract methods (again it doesn't need fields!) An other solution
would be a 'const' keyword... Well... I just hope JavaSoft will do something
about situations like that.


Submitted On 25-AUG-1998
kriff
Class (static) methods in interfaces do make sense
but only if they don't impose requirements on any
implementing classes. In my view, class methods in
interfaces must be fully defined with a complete
implementation.
Consider the practice of placing constant values
in interfaces (possibly inner-interfaces). To use
the constants in classes you have the option of
writing "Interface.CONSTANT" or implementing the
interface and simply writing "CONSTANT". The latter
is a convenient shorthand for "Interface.CONSTANT".
I propose that class methods work in a similar manner.
Only one implementation for a class method ever 
exists so there's no confusion about which one is used.
By implementing the interface, your class gains
access to its static methods via the same shorthand
notation used for constants.
Suppose the class java.lang.Math (which has no
instance methods) were instead an interface. Then
it would still be possible to write "Math.sqrt(d)"
but you would also be able to write the following
class:
public class Foo implements Math // for shorthand access to math functions
{
    // Calculates the length of the third side in a right-angled triangle
    public double hypotenuse(double a, double b) { 
        // Use Math.sqrt
        return sqrt(a*a + b*b);
    }
}
I don't think this pollutes Java's notion of 
"inheritance" because it provides a simple and
logical extension to the current behaviour. The 
only changes necessary are likely to be to the
compiler and the class verifier.
Allowing interfaces to define static methods without
providing an implementation would require some
concept of an "abstract static" method. That implies
that static members are inherited by sub-classses
and may be overridden (or must be, in the case of
abstract methods). This arrangement is completely
opposite to the way Java has worked for years.
Changing it now is not worth the effort.


Submitted On 20-JUL-1999
dleuck
Correction to my last comment...
The last line should read:
int value = min(sortedMap.get(key), 0);
Sorry :-)


Submitted On 20-JUL-1999
dleuck
I can't think of any reason not to support static methods in interfaces in the
manner described by kriff.   They certainly don't introduce any complexity that
doesn't already exist as the result of allowing static fields in interfaces. 
Further, static methods are arguably even more useful.  Wouldn't it be nice to
have all the static utility methods in Collections, Lists, and Maps exist in
the Collection, List, and Map interfaces!  Kriff's Math interface is another
excellent example.  Code looks cleaner, is more readable, easier to write, and
less error prone.  
Given that you have already conceded that changes to the JLS and JVMS in the
next major release will be necessary to support glaring omissions such as
covariance and parametric polymorphism (Generics),  why not remove this
pointless and annoying restriction.  You probably won't want to make many more
changes to these specs so it seems best to fix the obvious things all at once.
It seems like there is some law that Java code must look overly verbose and
clunky.
Just looking at the source to a class I happen to have open...
...
SortedMap sortedMap= 
Collections.synchronizedSortedMap((SortedMap)sortedMaps.get(mapKey));
int value = Math.min(((Integer)sortedMap.get(key)).intValue(), 0);
...
Arg!
With the proposed changes (covariance, generics, interface static methods) the
above example would read:
...
SortedMap sortedMap = sortedMaps.get(mapKey).synchronize();
int value = min(sortedMap.get(key));
The code is 1000X more readable!  No abbreviations were used and no
auto-documented information was lost!
Java is awsome but it could be so much better with just a few changes!


Submitted On 11-AUG-1999
wehe
in over two years of using Java I was in bad need of STATIC methods in
interfaces for three times - alternate solutions exists but in those cases I'd
still use static interface members; after all the stuff I'v done with this fine
language, this prob is the only *serious* dis-like I encountered so far. Please
fix this!


Submitted On 03-SEP-1999
danaw
Allowing static method signature definitions in 
interfaces would be very useful.  It also could
not be abused: each concrete implementation would
simply have to define the method.


Submitted On 11-AUG-2000
eblake
It might be a good idea to make all static methods in an
interface implicitly final.  Then, their implementation must
involve only methods that are also defined in the
interface.  This would prevent an implementation from hiding
the static version; so that it is not possible to change the
behavior of the interface method.  This becomes an issue
because static methods only hide, not override.  For
example, if interface I declared a static method m() that is
not final and class C implementing I declared a method of
the same signature but different behavior, the user would
get different results depending on whether they call I.m()
or C.m(); and in the case of setting a variable of type I to
contain an object of type C, it is not obvious which method
would be called.

An abstract static method just does not make sense; that
would require static methods to be overridable and
polymorphic, and massively change Java.

If a class has multiple ancestors (the superclass and/or one
or more superinterface) with a static method of the same
type signature, regardless of return type or throws clauses,
then that class cannot inherit either static method by the
simple name because it would be ambiguous which version to
call. In such a case, however, the methods are still
accessible; it should not be a compile-time error that there
are multiple accessible versions, but every access of that
method name requires the reference to the class or interface
where it is defined.

For example:
interface I {
  static void message(int i) {
   System.out.println("The number is " + i);
 }
}
class A {
  static String message(int i) throws Exception { //
implicitly final
    if (i < 0)
     throw new Exception("Argument must be positive");
    return String.valueOf(i);
  }
}
class B extends A implements I {
  static void foo() throws Exception {
//    message(1); // invalid, as B has two ancestors that
define message,
                     // it inherits neither version
    A.message(1); // valid
    I.message(1); // valid
  }
//  static void message(int i) {} // invalid, as I.message
is implicitly final
}


On the other hand, you could allow for non-abstract instance
methods in an interface.  These would provide default
behavior defined in terms of the other instance methods of
the interface.  These should not be final, as instance
methods are polymorphic so only one type of behavior can
ever be observed if a user overrides the default to be more
efficient.  (Compare this behavior to abstract classes). 
However, the compiler will need to determine whether a
method is abstract or not by noticing if the method has an
implementation, since Java currently makes all interface
methods implicitly abstract.

For example:
interface Communicator {
  // sends a message to c
  void send(String s, Communicator c); // abstract
  // receives a message from c
  String receive(Communicator c); // abstract
  // sends a message, and waits for the response from c
  String query(String question, Communicator c) { // not
abstract or final
    send(question, c);
    return recieve(c);
  }
}


Submitted On 11-AUG-2000
eblake
It might be a good idea to make all static methods in an
interface implicitly final.  Then, their implementation must
involve only methods that are also defined in the
interface.  This would prevent an implementation from hiding
the static version; so that it is not possible to change the
behavior of the interface method.  This becomes an issue
because static methods only hide, not override.  For
example, if interface I declared a static method m() that is
not final and class C implementing I declared a method of
the same signature but different behavior, the user would
get different results depending on whether they call I.m()
or C.m(); and in the case of setting a variable of type I to
contain an object of type C, it is not obvious which method
would be called.

An abstract static method just does not make sense; that
would require static methods to be overridable and
polymorphic, and massively change Java.

If a class has multiple ancestors (the superclass and/or one
or more superinterface) with a static method of the same
type signature, regardless of return type or throws clauses,
then that class cannot inherit either static method by the
simple name because it would be ambiguous which version to
call. In such a case, however, the methods are still
accessible; it should not be a compile-time error that there
are multiple accessible versions, but every access of that
method name requires the reference to the class or interface
where it is defined.

For example:
interface I {
  static void message(int i) {
   System.out.println("The number is " + i);
 }
}
class A {
  static String message(int i) throws Exception { //
implicitly final
    if (i < 0)
     throw new Exception("Argument must be positive");
    return String.valueOf(i);
  }
}
class B extends A implements I {
  static void foo() throws Exception {
//    message(1); // invalid, as B has two ancestors that
define message,
                     // it inherits neither version
    A.message(1); // valid
    I.message(1); // valid
  }
//  static void message(int i) {} // invalid, as I.message
is implicitly final
}


On the other hand, you could allow for non-abstract instance
methods in an interface.  These would provide default
behavior defined in terms of the other instance methods of
the interface.  These should not be final, as instance
methods are polymorphic so only one type of behavior can
ever be observed if a user overrides the default to be more
efficient.  (Compare this behavior to abstract classes). 
However, the compiler will need to determine whether a
method is abstract or not by noticing if the method has an
implementation, since Java currently makes all interface
methods implicitly abstract.

For example:
interface Communicator {
  // sends a message to c
  void send(String s, Communicator c); // abstract
  // receives a message from c
  String receive(Communicator c); // abstract
  // sends a message, and waits for the response from c
  String query(String question, Communicator c) { // not
abstract or final
    send(question, c);
    return recieve(c);
  }
}


Submitted On 26-SEP-2000
penses
There is another issue here.  The whole reason for using 
interfaces is to allow code to be unconcerned with the 
implementation aspects of the methods.  If you are 
providing an interface that is meant to hide platform 
specific implementations, you would be unable to provide a 
static final method with an implementation within the 
interface because you have to know at compile time which 
platform you would be running on, which defeats the entire 
purpose of using Java to begin with.  If we allow the 
declaration of static methods in interfaces( Which I 
recomment strongly), we have to allow the implementing 
class the ability to implement the body in any way the 
class sees fit.


Submitted On 19-DEC-2000
schapel
Because static methods are not polymorphic, I think allowing
interfaces to implement static methods would be horribly
confusing and not very useful at all. It would be much more
useful to allow non-static methods to be implemented in
interfaces. But the whole reason that is disallowed is that
Java allows multiple inheritance of interfaces but not
multiple inheritance of implementation. Why not go all the
way and allow Java classes to inherit from several classes?
Then we can get rid of interfaces altogether!

In all the comments above, I can't find one good reason for
allowing interfaces to have static methods. The one example
where it does any good at all is where Math is an interface
so that you can inherit from it and replace Math.sqrt with
sqrt. Even though it is somewhat useful, that trick is
merely syntactic sugar and is less clear than simply
always writing Math.sqrt. Could someone give an example
where putting a static method in an interface really does
make the code clearer and more understandable?

Lastly, I should point out that changes to the JVM are not
necessary to support generics and covariance of return type.
The GJ compiler
http://www.cs.bell-labs.com/who/wadler/pizza/gj/
supports both of those features with current JVMs. These
two features, as well as adding const, would allow Java to
catch more errors at compile time. Can anyone give a similar
benefit from adding static methods to interfaces?


Submitted On 21-DEC-2000
KizubM
Once again.
Static methods in an interface may be used as _dynamic_ 
methods of an interface. It's simple - compiler may just 
replace
interface X {
void foo() {...}
}

with

interface X {
static void foo(X this$) {/*use this$ in place of this*/}
}

Multiple inheritance - is a bad way of OO language design
(for languages that use _fast_ virtual table dispatching,
in contrast to _slow_ message dispatching like in 
SmallTalk).
You don't really realize how complex is multiple 
inheritance, and how many modifications language requires,
and how it slow down implementation.

In contrast - static methods (that allow compiler to 
emulate dynamic methos - by providing 'default' method 
implementation) do not make language and virtual machine  
more complex or slow. This functionality already exists in 
JVM - it's required to execute static class initializer to 
initialize fields of interface.

THE JVM NEEDS NO CHANGE. THE ONLY CHANGE REQUIRED - IS 
VERIFYER - is to remove additional checks from java 
verifyer, that doesn't allows any static methods, except 
<clinit> method, to be declared in interface. That's all. 
It's so simple. It requires an hour of work of any stupid 
programmer. It doesn't breaks anithing. I don't understand 
why it takes soooo loooong to fix this small issue.


Submitted On 22-DEC-2000
schapel
KizubM,

There are several problems with your proposal:

1) At the same time you denounce multiple inheritance, you
provide for multiple inheritance in your "Java compiler".
For example, what if I have two interfaces and a class, in 
your extended language, as follows:
interface X { void foo() { /* one implementation */ } }
interface Y { void foo() { /* another implementation */ } }
class Z implements X, Y { }
which implementation of foo() should Z inherit? Are you for
or against multiple inheritance?

2) The change to the verifier you suggest does break
something. It breaks the ability for newer class files to
work with older JVMs. An incompatability this huge should
not be taken lightly at all. How long it takes to change the
verifier code is not the issue. Rather, the tremendous
inconvenience to millions of programmers and users is.

3) This huge change would simply allow you to get away with
sticking the static method implementation in the interface
file, rather than creating a dummy class file. Making this
change to the JVM sounds like a huge risk to gain just a
small reward.

Could someone point out a more significant benefit to
allowing static methods in interfaces? Or a way of adding
static methods to interfaces that has a lower risk?


Submitted On 26-DEC-2000
KizubM
1. Correct compiler should produce error here.
2. Yes and no. With older JVM, which is runned without '-verify' switch the code will run normally.
For latest JVM, which have '-verify' switched on by default - they will not work...
But if you care about compatibility with current JVM - you'll have no chance
to improve JVM at all. For example, when java will have parametriezed types - new
classes will not run on older JVMs, right? Does this mean, that parametriezed
types should not be added to java? Backward compatibility is a good thing, but..
Another example - when inner classes were introduced in java - JVM was not
changed, and, to access private fields and methods of outer class from inner
class the java compiler needs to created special wrapper functions. This
makes compiler more complex (and potentially buggy), and access to
those private fields and methods more slow. And for what reason???
New classes (that use new core API classes, like java.util containers)
can't be executed on older JVM, but perfomance is still affected by
that desition to not change JVM.
Correct solution is known - the 'target' switch of java compiler.
For older JVMs it can generate additional classes, and for newer JVMs
it may use static methods in interfaces. For older JVM it will need
to create wrapper methods to access private fields in outer classes,
and for newer JVM its possible to store some info about less restrictive
rules for private members access. And so on.
3. If JVM is to be changed (for the reason described above) - why not
to add functionality of 'default method implementation' and
'virtual fields' to java language itself? At least, allowing static
methods in interfaces now - will help to add this to java language later.
I mean, if this restriction will be removed from verifyer _now_ -
it will prepare the ground to extending java language lately.

Actually, restriction that interface may have no static methods
or static non-final fields - is a mistake that was done when
java was too young. Even if java as language wish this restrictions -
why to enforce this restrictions for others lanaguages, that use
JVM as a 'simple and processor-independent architecture' ?
JVM != java language.

PS As for your note about gj - it supports covariant return
types and type parametriezation with a lot of restrictions.
A LOT. Some of them may be fixed by adding runtime info
about type parameters to  code (which makes compiler
a lot more complex and buggy, belive me), but some
can't be fixed with current JVM (for example, if you
have 'class Test<A>' - you can't have 'Test<A>[]'
type).

PPS A'm not for multiple inheritance as it's implemented
in C++. It haso some problems with deep inheritance
(like 'virtual parents'), and requires some manipulation
with 'this' pointer on method call (which slows calls)
and requires separate virtual tables for each class,
thus those virtual tables becomes too huge in memory.
Sometimes multiple inheritance of C++ may be
replaced by interface's static methods, sometimes by
forwarding (delegation) to class' field, and always
by dynamic message dispatching (like in Smalltalk -
but this is very slow type of method invocation,
and requires global optimization, like in Cecil, to have
any acceptable speed).



Submitted On 04-JAN-2001
Parkway
I don't quite understand the last discussion between KizubM
and schapel. I thought we were asking for static methods here.
interface X { static void foo() { /* implementation */ } }
interface Y { static void foo() { /* implementation */ } }
class Z implements X, Y { }
This should compile unless class Z tries to implicitly refer
to foo() as the reference is ambiguous.

P.S. foo() is implicitly final because it is static, but it
may be synchronized.
P.P.S. It would probably help to have private variables.


Submitted On 05-JAN-2001
jessh
I asked Sun explicitly via an RFE to allow interfaces to 
include method implementations but still not field - as per 
MartDesruisseaux's suggestion above.  Sun rudely said this 
was multiple inheritance of implementation and said Java 
would *never* under any circumstances includes this.

I understand disallowing multiple inheritance of *fields* 
as this makes object layout a mess, but the ability to 
provide default implementations of methods in terms of 
other interface methods would eliminate a lot of stupid, 
redundant code and/or external classes that implementors 
have to somehow know to call from to provide default 
behaviors.


Submitted On 06-JAN-2001
KizubM
2Parkway
We were discussing making _non_static_ methods in 
interfaces to be default implementation of methods,
if a class that implements this interface lacks
this method, for example

interface I { int foo() { return 1; } }
class C implements I {}
class D implements I { int foo() { return 2; } }

This actually is not the topic of this RFE, but
is relative to it, since compiler may always generate
something (instead of above) like

interface I { static int foo(I this$) { return 1; } }
class C implements I { int foo() { return I.foo(this); }}

Also, making static methods 'final' is meaningless - they
are not 'overriden', so, 'final' modifier, that prevents 
overriding is meaningless.

2jessh
I agree. Disallowing static (non-final) fields
and static methods and non-static methods (as default 
implementation) is an unundastandable limitation of
both Java and JVM.


Submitted On 08-JAN-2001
KizubM
Why?
1. Because it will make JVM more "correct". The desition that JVM may not allow
static methods in interfaces was wrong from the begining.
It doesn't make java simplier, after all - it makes it more complex.
2. Languages are for programers, not programers for languages.
If I feel that a piece of code fits this place - why should I move it
to another place?


Submitted On 08-JAN-2001
schapel
>If JVM is to be changed (for the reason described above) -
>why not to add functionality of 'default method
>implementation' and 'virtual fields' to java language 
>itself?

Rather than asking "Why not?", how about answering my
question of "Why?".

If you want to implement a method in Java, put the method
in a class. Sometimes that means writing a "dummy" class to
contain the method. What is the advantage of putting the
method in an interface? Does it make it easier to write
Java programs? Does it make Java run faster or use less
memory? Please give examples where the advantage of putting
static methods in interfaces is clearly demonstrated.

Even if the JVM is changed, we'd have to wait until the
release after 1.4. That means the earliest this could be
changed would be around 2003. The chances of this being
changed _now_ is zero.


Submitted On 15-JAN-2001
leolore
To restate this request, we need a way to indicate that a 
method whose scope is the class, (not object) must be 
implemented by any class declaring this interface.

Even if the interface could not declare the method as 
static, if the class could actually implement it as static, 
it would be better than it is now. Currently, if the method 
is defined in the interface, the compiler disallows the 
implementation from being static (so it does impose a 
constraint on the class method).


Submitted On 12-FEB-2001
schapel
>The desition that JVM may not allow static methods in 
>interfaces was wrong from the begining.

So you're saying we should allow static methods in
interfaces because not allowing them is wrong? Gee, does
that argument sound circular to anyone? :-)

Ok, please explain why it is wrong not to allow static
methods in interfaces, and give an answer more meaningful
than it's correct to allow them. Some example code would
help in demonstrating your point.

I'm not sure if this RFE is for adding abstract static
methods in interfaces, as leolore says, or if this RFE is
for allowing implementations of static methods in
interfaces. If you want abstract static methods, you
probably should vote for Bug 4193604 instead.


Submitted On 16-FEB-2001
KizubM
I gave example. See above.
Allowing static methods in interfaces (even not in java
language - just in JVM), will allow some compilers that
extends java and some compilers for non-java languages to
generate more effective code and be a bit simpiler.
It will also prepare JVM for future (possible) changes
of java language that will allow interface methods be
default implementation of classes. Isn't this enough?

I'm tired of this RFE. All I wished is just a small
chage in verifyer - just removing one line of code, that
complaince about static methods in interfaces that
has names others then <clinit>. That's all. I even
do not ask to change java language specs.

And this RFE was submitted 4 years ago, and that
stupid line in verifier was not removed until now.

Ok, I'm not intrested in java anymore. Stay with it.
I'll do my own VM. GNU VM.

Thanks to all and good bye.



Submitted On 22-FEB-2001
schapel
OK. It sounds like Java is not for you. Bye!

I should point out that any change in the verifier that 
allows a newer form of class file will be a bigger change 
to the JVM than we've ever seen. To this day, any program 
compiled with javac 1.3.1 will work with the 1.0.2 version 
of the JVM, as long as you stick with older APIs and don't 
use the -target switch. See
http://java.sun.com/j2se/1.3/compatibility.html
for details. With a change to how static methods work 
(either allowing static methods in interfaces, or allowing 
abstract static methods in interfaces and abstract 
classes), Java would lose this downward binary 
compatibility. Java applets compiled with the new compilers 
would not work in any browser. Java servlets compiled in 
this way would not work with any current servlet engine. Is 
this the price you're willing to pay for this small feature?

I'm against any change in binary format that would make 
Java not downward binary compatible with older JVMs, unless 
it has some overwhelming benefit to many thousands of Java 
programmers, not just programmers who write compilers for 
Java language extensions and non-Java languages.

Could someone post some code written in current Java, and 
written in a version of Java that allows static methods in 
interfaces, and demonstrate how such a change to the 
langauge makes the program easier to write, easier to read, 
easier to test, faster, or use less memory, or give any 
other tangible benefit to Java programmers or users?


Submitted On 22-MAR-2001
gafter
Your proposed "little" change to the verifier (stop
complaining about static methods in interfaces) would be
easy to add - or rather, remove - from the VM. But don't
exepct the VM to treat these methods the way you want just
because the verifier doesn't complain about them.

I haven't heard a coherent and complete description of the
language change desired.


Submitted On 02-APR-2001
KizubM
Gafter, first of all I didn't expect Java will start to
understand static methods in interfacese after verifyer will
allows them in bytecode.

In kiev compiler your able to declare static and non-static
methods in interface, and non-static methods will be
emulated via static methods of interface and auto-inserted
method (in each class that implements this interface, and
do not have method with the same name and signature) that
delegates it's functionality to static method in interface.

As for changes of Java language and JVM - there may be
some degrees of completnes.

1. Minimal changes - allow those static methods in
verifyer and let non-java or extended java compilers
to use this functionality.
2. Minor changes - add ability to JVM and Java to use
non-static methods in interfaces as default implementation,
if a class, that implements this interface, do not provides
it's own implementation.

3. More changes - add to java 'virtual' fields - fields
that always accessed through automatically generated
(if not provided manually) pair of getter/setter methods.
This is commonly used technique - properties in borland's
pascal or in C#, for example. Also, since interface cannot
have non-static fields, they have to be all 'abstract',
i.e. there will be only two abstract getter/setter methods,
without fields itself. Of cause, programer may provide
his own implementations of those getter/setter methods
(so, they not needed to be always abstract).

4. Finally, the most full approach - allow static and
non-static fields and methods in interfaces. Non-static
methods will work as default implementation, and non-static
fields will be automatically added to the class, that
implements this interface (if that non-static field is
not 'abstract'), and all fields of interface will always
be accessed through getter/setter methods (automatically
generated, if not provided explicitly).

For example, Dylan uses last approach to implement
multiple inheritance - it generates getter/setter
methods for each field and access fields only via
those methods.

Yes, if anything more then just verifyer changes will
be added to java - there will be problems with old
semantic of java lanaguage - calling super methods,
for example. If class provides it's own implementation
of method - can it call super.theMethod() to call
intterface's implementaton? And which super-method to call,
if both interface and super-class have non-abstract
method?

But, even if java will have all those changes - it will
still be very few of those I wish to see. Delegations,
multimethods, closures and more... So, JVM will be the
target VM for next version of kiev compiler.
JVM is too restrictive to be convinient and efficient
for real-world applications (your can't even write 
efficient enought JVM using java itself), and is
too complex from the other point of view (trying to
solve problems with the needs of processes,
security, closures extremly needed by GUI library,
and so on).


Submitted On 12-APR-2001
enicholas
You know, in reading these comments I'm struck by the fact that many of
you arguing for this feature just don't have any clue what you're talking
about.  I'm sorry, but it's true --

"It might be a good idea to make all static methods in an interface 
implicitly final."

Static methods cannot be final.  Since the concept of overriding a static
method doesn't even exist, final is meaningless.

"To restate this request, we need a way to indicate that a method 
whose scope is the class, (not object) must be implemented by any 
class declaring this interface."

Hmm.  This would amount to declaring an abstract static method.
What the %&#@ is an abstract static method supposed to be?
Has anyone actually thought about this at all?

I'm with the other naysayers here ... until you stop whining and
write up a coherent, complete, well-thought-out request for a
change to the language, which explains exactly why this is a
Good Thing, this is a silly request.  Particularly since nobody
seems to actually understand what is involved, or even what
they're asking for....


Submitted On 08-MAY-2001
MiguelM
I would like to see interfaces allow methods with package access as well as public. Sometimes my interfaces 
are only available within my package, and it doesn't make sense to force the implementation to be public.


Submitted On 17-MAY-2001
dpc2
As for static methods (I'm not going to comment on the hash 
of comments on other topics here) in interfaces, one can 
define a public nested class (I often use the name Methods) 
inside an interface and put static methods in there:

public interface Whatever {
    public static class Static {
        public static void doSomething() {
            // whatever
        }
    }
}

* * *

Whatever.Static.doSomething();

* * *

My two cents is that this would be useful from a design 
point of view for methods that operate on an instance, or 
instances, of the interface (e.g., a toString()-like 
method, sorting methods which sort arrays of the interface).


Submitted On 21-JUN-2001
rreyelts
Generally speaking, this problem seems better solved 
through structural conformance than through Java 
interfaces' named conformance. 

So, why don't we add support for a parametric, polymorphic 
interface that operates based on structural conformance and 
call it a concept?

For example, 

/** 
 * Any class that has the method, foo, _implicitly_ 
 * implements the Fooable concept. 
 * 
 */
public concept Fooable {  
  public void foo();
} 

/** 
 * This is a generic class. The template parameter 
 * F, must conform to the concept, Fooable. 
 * 
 */
public class Foo<F extends Fooable> {  
  public void foo( F f ) {    
    f.foo();  
  }
} 

/** 
 * Implicitly 'implements' the concept, Fooable. 
 * 
 */
class A {  
  public void foo();
}

This is easily extended to creating concepts which have 
static methods:

public concept FooFactory {
  public static FooFactory createFoo();
}

God bless,
-Toby Reyelts


Submitted On 25-JUL-2001
mikaelstaldal
This doesn't seems to a good idea. Currently, you cannot 
have any real _code_ in an interface, and I think that's a 
good thing.


Submitted On 01-AUG-2001
danaw
I think that the discussion of this enhancement has taken it
farther than the original request.
What I personally am interested in is merely the ability to
have a static signature definition, for example:

  // get the TYPE of handler used by
  // members of the concrete class
public static String getHandlerType();

This would not involve adding the ability to put code in an
interface, and would be a much simpler change.


Submitted On 02-AUG-2001
mikaelstaldal
The ability to have static method *signatures* in an 
interface might be a good idea. However, first we need to 
allow abstract static methods in abstract classes, and the 
semantics for that needs to be investigated.


Submitted On 03-AUG-2001
schapel
The discussion seems to go around in circles, never leading
anywhere.

It doesn't make sense to have abstract static methods,
because when you call a static method, the compiler must
know which class's method you're calling. Therefore, the
ability to "force" a subclass to implement a static method
adds no new capabilities to the language.

Abstract is useful for polymorphic methods, so that you can
force subclasses to provide their own implementations of a
method, where the class whose method is called is determined
at run time rather than at compile time.

Maybe someone could finally explain *why* having abstract
static methods would be useful -- I've certainly never seen
any explanation.


Submitted On 10-AUG-2001
dnoyeB
Interfaces should not impose constraings on class methods 
contrary to the evaluation comments.

Interfaces are always public, else they make no sense.  I 
have never heard of a protected, packate, or private 
interface methodology.

The evaluator completely missed the point here I believe.  
This is the point

interface x
{
void do1();
void do2();
void do3();
void do4();
}

class y implements x
{
void static do1(){}
void native do2();
void synchronized do3(){}
void do4(){}
}

The point is that the class above has only 1 error and that 
is the static method.  for some reason static methods are 
not able to fulfill the requirements of the interface, yet 
they should be.  This is not an RFE, this is a BUG. 

I cant think of a logical reason why a static method can 
not fulfill the requirements of the interface?


Submitted On 14-AUG-2001
HPietsch
Calling an interface method is a completly different
instruction than calling a static method. And ofcourse the
resulting native code after JIT compilation differs too. The
first needs a lookup and the latter is a direct call. And
both have a different number of arguments as the first
provides an instance.
Adding the code for letting both things work together
creates a significant overhead in native code generation for
a feature that might not be used very often.


Submitted On 16-AUG-2001
glenn42
if interfaces are being opened up, why not allow them to
specify constructors also?

say, by allowing the interface to include its name (without
a return type) as the method name. 


Submitted On 27-AUG-2001
steveftoth
to dnoyeB:

the reason that 
void static do1(){}
 is invalid is because all methods of an interface are 
virtual or polymorphic.  All static methods are NOT 
polymorphic.  When you 'override'  a static method, you are 
really 'hiding' it.

like below

public class a {
    public static void test() { 
    System.out.println("test");
    }
  public static void main(String  [] args )
  {
    new a().test();
    new b().test();
    ((a)new b()).test();
  }
}
class b extends a {
  public static void test() {
    System.out.println("test subclass ");
  }
}

The main produces the result 
test
test subclass
test

interfaces cannot be used to specify static methods because 
all static methods are linked at compile time, not run time 
like regular instance methods.


Submitted On 25-SEP-2001
CChrisB
I think interfaces should not only include static methods 
but constructor prototypes. 


Submitted On 07-OCT-2001
dnoyeB
to SteveFToth

The interface is not supposed to specify static.  That is 
not my desire.

However, a class which implements an interfaces 
requirements should not be shunned because one of the 
implemented methods happens to be static.

All an interface should care about is that its requirements 
are saticfied.  If you say you implement the interface, 
than anyone who calls the class should be able to call the 
methods on the interface.

I see your point about polymorphic issue.  But this is for 
the programmer to work out.  He should know what he is 
doing if he wants to make it static.  I don't see this as a 
source of either confusion or errors.  Its just hand 
holding in my opinion and its restrictive.

But you understand that my main point what that the 
EVALUATOR does not _understand_ the issue.  Which is 
probably why we have never received any type of response to 
it.


Submitted On 15-OCT-2001
weic
to have static methods in interface, we first need to make 
the static methods like instance methods inheritable.  I am 
asking all along for treat static as attributes to a 
default Class object with the same power of inheritance as 
instance and have a "this" constant.

To see why we need this, just think of an abastract class 
implement this interface partially, and leave the static 
methods to the subclass.


Submitted On 25-OCT-2001
schapel
To see why we *don't* need this (inheritable static
methods), just think of using a static inheritable method.
Now, simply remove the static keyword, and it works in the
current Java language.

In other words, if you want a method to be polymorphic, you
need do nothing more than not make it static. If you want to
show that this thinking is incorrect, please post some
example code together with an explanation of why polymorphic
static methods would be of any benefit to making the code
clearer.


Submitted On 31-OCT-2001
cdbennett
As far as final and synchronized methods, this is again not 
part of the interface. 
final: not possible! Because all methods in an interface 
are abstract, and methods cannot be both final and 
abstract, wondering why this doesn't work shows a true lack 
of understanding of the language.
synchronized: not actually part of the method signature. 
For example, if you have a superclass with a 
method "synchronized void foo()", you can override it in a 
subclass of that class with a method "void foo()". It only 
affects the way the method executes, not the signature.


Submitted On 31-OCT-2001
cdbennett
No. An interface is there to support polymorphic behavior 
and encapsulation. Polymorphism doesn't work if you don't 
have a class *instance* to call an operation on. Class 
methods cannot be polymorphic.


Submitted On 03-NOV-2001
Ixchel
A reply to the previous poster:
Yes, a static method in an interface could not be 
polymorphically dispatched. That does not, however, make 
them useless.

Consider putting static methods in an interface to support 
common behavior (utility routines) which can be implemented 
using only that interface's methods. For instance:

interface Number {
    public static Number subtract(Number foo, Number bar) {
         return bar.negate().add(foo);
    }
}
Now, granted there are possibly better ways to do the above 
in specific cases (such as adding a 'subtract' method to 
Number in the above case), but this approach does have the 
nice property that the 'subtract' method can be used by all 
implementations of the Number interface, even if they all 
have different superclasses. Most other approaches that I 
have seen either require all of the implementations to have 
the same superclass, require duplication of code, or 
require an apparently unrelated class (e.g. NumberUtils) to 
contain the static methods. All of these introduce needless 
complexity.

Another desirable usage of static methods would be for 
singletons and factories which have their implementation 
supplied at runtime. For example:

interface MyClass {
    public static MyClass createInstance() {
         return Class.forName(System.getProperty
("TypeOfMyClass")).newInstance();
    }
}

This allows one to construct a new instance of a class 
implementing the MyClass interface by calling 
MyClass.createInstance(), without knowing what actual type 
will be created. Without static methods in an interface, 
this has to be done by some other, less convenient method, 
such as with a factory object that exists solely for the 
purpose of providing such an instance. (Note, for instance, 
the DateFormat, TimeFormat, etc. classes which are declared 
via an abstract base class in order to allow similar usage, 
but which could be declared via an interface if interfaces 
could support static methods. This would allow their 
subclasses not to be forced to inherit from the abstract 
base class.)


Submitted On 03-NOV-2001
GalB
Class methods (static) are not polymorphic. For this reason, declaring a 
static method in an interface makes no sense. An implemented class will never 
be able to "implement" such a method, and a user of such an interface will 
never be able to call the "class method" and get the implemented version.

I'm sure someone else said this allready, but the amount of comments I had to 
read to find that out is overwhelming :)

Gal


Submitted On 07-NOV-2001
schapel
Here's a way of implementing a static method in an interface
in current Java without requiring implementations of the
interface to have the same superclass, duplicated code, or
an apparently unrelated class:

public interface Number {
  class Util {
    public static Number subtract(Number foo, Number bar) {
       return bar.negate().add(foo);
    }
  }
}

To call the subtract method anywhere, just write:
  Number c = Number.Util.subtract(a, b);
for example. Granted, it takes 5 extra characters for every
call to the method, but the code is no harder to read or
modify than if the static method were directly in the
interface, and adding a feature to the Java language that is
not compatible with older JVMs is far worse than simply
putting the static methods in a nested class.


Submitted On 16-NOV-2001
danaw
schapel:  Your workaround nicely handles what I had wanted
the static methods for.  Thank you.

However (now that I've read all the suggestions), I think
that dnoyeB's idea --allowing a static method to meet an
interface method definition-- would solve certain things
more simply.  
It would be consistent with the concept of interfaces, it
would be backward compatible (since it would simply allow a
interface method to be implemented as either a static or an
instance), and it would not tamper significantly with the
way Java is defined.

This would allow a interface method to be implemented as a
static final for faster execution for the classes that could
take advantage of it, while permitting other classes to use
instance methods if they needed to.




Submitted On 16-NOV-2001
danaw
My above comment, about solving things more simply, means I
do not think it is wise to add method bodies to interfaces,
as some have been advocating.
(Also, it is now obvious that it is unnecessary, thanks to
schapel's code template.)



Submitted On 16-NOV-2001
jonathanfinn
If (and it's a big if) static methods could be added to 
interfaces without introducing various problems discussed 
above, then here's one use for them:

The methods in the java.util.Collections class, which are 
just a bunch of static functions, coulds have been put in 
the java.utils.Collection interface. This would have been 
neater.

There are other examples like this.


Submitted On 19-NOV-2001
schapel
>...Allowing a static method to meet an interface method
>definition-- would solve certain things more simply.
>
>It would be consistent with the concept of interfaces, it
>would be backward compatible (since it would simply allow a
>interface method to be implemented as either a static or an
>instance), and it would not tamper significantly with the
>way Java is defined...

First, what things would allowing this solve? It seems to me
that if you want to implement an interface, you provide
appropriate implementations for the methods. What is the
problem with that? Could you provide some code that would be
easier to write or maintain if static methods were allowed
to implement interface methods?

Second, allowing static methods to implement interface
methods is not at all backwards compatible with older JVMs.
Static methods are always called by the invokestatic
bytecode instruction and interface methods are called by the
invokeinterface bytecode instruction. If you try to
implement an interface method with a static method, you get
a NoSuchMethodError in current JVMs. Code that uses this new
feature would not work in older JVMs.

Third, allowing static methods to implement interface
methods does "tamper with the way Java is defined".
Specifically, it makes static methods polymorphic where they
aren't currently. If you want a method to be polymorphic,
simply don't make it static.

Lastly, the claim is made that there would be a performance
benefit from this JVM change. I don't see why there would be
any performance gain... static methods are currently
generally faster than non-static ones because they are not
polymorphic. Calling a static method polymorphically would
be slower than calling it non-polymorphically, so there
should be no performance gain.


Submitted On 17-JAN-2002
SJS
Static methods in interfaces is just, well, *wrong*.

For those who really, really, really need it, schapel's
workaround (embedded Util class) seems to be the least
intrustive workaround.

On the other hand, dnoyeB's insightful comments and
explanation of what the actual problem might be can also
be taken care of by a work-around (rename the static method,
and have a non-static method call it):

public interface Foo {
   void doit1();
   void doit2();
}

public class Bar implements Foo {
   static void doit1_static() { ... }
   void doit1() { doit1_static(); }
   void doit2() { ... }
}

Perhaps there should be a way to vote *against* an RFE?


Submitted On 21-JAN-2002
dufort
Guys, let's keep the Interfaces as clean as they are right 
now. I can cope with bare-bone interfaces, and let helper 
classes do the static job... no problem with that!

Whenever I need shared static functionalities, I define 
helper classes (a stateless class with all methods 'public 
static'). If I need a restraint on visibility, I make the 
methods package-visible. And that's all.

And by the way, use an Abstract class to define common 
private functionalities; anyway interfaces should define 
roles, and not well-defined behaviors.

If there is anything I would like to see in an Interface, 
it's a 'synchronized' modifier. But that's another story.


Submitted On 30-JAN-2002
schapel
Allowing methods in interfaces to be synchronized would
serve no purpose. Synchronization is an implementation
detail... a method that overrides a synchronized method need
not be synchronized. See the Evaluation section at the top
of this page for a reiteration of this point.


Submitted On 05-FEB-2002
JPF
The compiler could translate :

public interface Number {
    public static Number subtract(Number foo, Number bar) {
       return bar.negate().add(foo);
    }
}

into:

public interface Number {
  class Static {
    public static Number subtract(Number foo, Number bar) {
       return bar.negate().add(foo);
    }
  }
}


and the call:
Number.substract(n1,n2)
into:
Number.Static.substract(n1,n2)


This way there is no need to change the VM.


Submitted On 08-FEB-2002
dstuart
static methods on interfaces?? whaat?

Guys, let's all try hard not to make silly RFE's. This 
would completely ruin the encapsulation that interfaces are 
meant to achieve. In fact, if I had my way, the static 
keyword would be REMOVED from the language, with the 
exception of fields.

If you need a static interface, then just declare your 
interface as if it weren't static, and then provide a 
method like "getInstance()" which implements a singleton 
pattern.

Guys, it's not rocket science. I hope that the people at 
Sun ignore this RFE, personally.

Now, there *might* be a tiny argument for synchronized, but 
I'm not sure there either.. I'd have to think about it.


Submitted On 08-FEB-2002
Dorceon
To SJS : In fact, I wanted to submit an RFE that anti-votes 
be added to the Bug Parade, but there didn't seem to be a 
category that it fit into... also, while voting down RFEs 
makes sense, voting down bugs really doesn't. "Thanks, but 
I'd like to KEEP this incorrect behaviour."


Submitted On 11-FEB-2002
steveftoth
This idea will not work.  For the reason that static is not 
polymorphic.  Since all static calls are resolved at 
compile time not at runtime, there will be massive 
confusion on which method to call.

Normally you have this.
class A  {
static void someFunction() {
System.out.println("class A");
}
}
class B extends A {
static void someFunction() {
System.out.println("class B");
}
}
now in your program 
B binstance = new B();
binstance.someFunction();
((A)binstance).someFunction();
will print out 
class B
class A
even though the instance is of type B, this is because 
static function calls are resolved at compile time.  They 
are not polymorphic.

If you were to add static functions to an interface, the 
runtime system would either a introduce polymorphism into 
static, thus changing the meaning of static, or it would 
not be able to resolve the call in a predictable way.

example
interface I {
static void i_func();
}
class AI implements I {
static void i_func() {
System.out.println("AI");
}
}
class BI extends AI {
static void i_func() {
System.out.println("BI");
}
}
ok, now we do...
I ainst = new A();
I binst = new B();
ainst.i_func();
binst.i_func();
((AI)binst).i_func();

which functions are called?
is it 
AI.i_func() , BI.i_func(), then AI.i_func()  or 
AI.i_func() , BI.i_func(), then BI.i_func()
the first way is similar to the way it is done now, where 
the call is resolved staticly.  the second way is done 
polymorphicly.  The second way violates the meaning of 
static.  

Also, if you add static functions to interfaces, what 
happens when you call...
I.i_func();  
is this an error?  you can currently define a static member 
variable for an interface and that works fine.  It doesn't 
make sence to define a polymorphic static meaning since you 
would need an instance of a class that implements the 
function for it to work.  

use factorys to create instances of classes that implement 
interfaces.  This RFE should be killed as it makes no sence.


Submitted On 25-FEB-2002
davidtribble
Polymorphic static methods, whether they are provided in base classes or
in interfaces, can be a useful thing.  There is nothing inherently "wrong" or
"evil" about them.  Whereas polymorphic methods are accessed through
an object of some base or derived type, polymorphic static methods are
accessed through the class type of some object.

Changing the JVM to allow them would be not that much different from how
it currently handles non-static polymorphic methods.  True, invoking a
polymorphic static method would require an extra level of indirection than
invoking a non-polymorphic static method (the extra level being needed to
dereference through the object's class type in order to access the
appropriate incarnation of the method), but this is not much of a argument
for rejecting the idea outright.

Consider a small example:

    class Base
    {
        static int getVersion() { ... }
        ...
    }

    class Der extends Base
    {
        static int getVersion() { ... }
        ...
    }

The getVersion() method allows me to retrieve the version number of an
object's class, without the overhead of passing a 'this' pointer to the
method.  Derived classes simply override the (static) method to provide their
own version numbers.

The concept is the same when we rewrite the example using an interface
instead of a base class:

    interface Face
    {
        static int getVersion();
        ...
    }

    class Der implements Face
    {
        public static int getVersion() { ... }
        ...
    }


Submitted On 28-FEB-2002
schapel
But changing the JVM to allow polymorphic static methods
would be inherently bad... it would be a change that is not
backwards compatible with older versions of the JVM. This
would mean that programs compiled by a newer compiler would
not necessarily run on older JVMs, even if the programs stuck
to the version 1.0 API. Are polymorphic static methods so
useful that it's worth making the most substantial change to
the JVM ever? You'll have an uphill battle convincing Sun of
that! If you want a polymorphic method, all you need to do is
make it non-static. Besides, the example you show is poor
because you shouldn't need to know at runtime which version
of a class you're running. Newer versions of classes and
interfaces should be binary compatible with older versions
so you never have to worry about versioning.


Submitted On 01-MAR-2002
sloa
??? Old jvm can't have new functionnalities
If you really think, you may encounter problems using the 'assert' keyword on 1.3- jvm :)
People need static methods declaration in interface.


Submitted On 04-MAR-2002
schapel
No, older JVMs don't have newer functionalities. Newer
source language features are compiled so that they run in
older JVMs. For example, inner classes are compiled into
normal, top-level classes. Just because the Java source
language changed doesn't mean the underlying JVM has changed!


Submitted On 05-MAR-2002
davidtribble
schapel wrote (THU FEB 28 08:26 A.M. 2002):
> But changing the JVM to allow polymorphic static methods would be
> inherently bad... it would be a change that is not backwards
> compatible with older versions of the JVM. This would mean that
> programs compiled by a newer compiler would not necessarily run on
> older JVMs, even if the programs stuck to the version 1.0 API.

You are saying that we shouldn't change the language if it affects the JVM,
because we will always want to run new programs on old JVMs.  That being
the case (and it's not always the case), then we shouldn't EVER change the
language in substantial ways.

We can implement polymorphic static methods in two ways.  The first way
involves adding a new JVM bytecode instruction, 'invokevirtualstatic', that
invokes a virtual static method, accessing the appropriate method via an
object's class type.

The second way simulates such an instruction with a sequence of existing
instructions, to access an object's class object (invoking 'this.getClass()'),
then invoking the specific static method in that class ('invokestatic').

The second method, while requiring more generated bytecode, will work
on older JVMs.


Submitted On 07-MAR-2002
schapel
> You are saying that we shouldn't change the language if it
> affects the JVM, because we will always want to run new
> programs on old JVMs.  That being the case (and it's not
> always the case), then we shouldn't EVER change the
> language in substantial ways.

No, I never said that. To clarify what I said as much as I
can, if you introduce a change to the JVM that is not
backwards compatible, there should be a very good reason for
doing so. In fact, there should be a good reason for making
any change in the Java language, even ones that are totally
backwards compatible.

Now, all we need is a very good reason to make static
methods polymorphic. Please provide an example of the use of
a polymorphic static method that cannot easily be written
using the current Java language. I've never seen one, so I
and the rest of us remain unconvinced.


Submitted On 03-APR-2002
_argv[-1]
I concur with those who believe that interfaces should be
able to specify constructors.


Submitted On 09-APR-2002
davidtribble
Reated RFEs: 4093687, 4291381, 4306573, 4491759

I submitted an RFE to allow constructor methods to be defined within an
interface definition.  Such constructors would then be required for any class
that implemented that interface.

The response from Sun was that I should post my suggestion on the java
newsgroups (like news:comp.lang.java.programmer) and see what kind of
support there was for the idea.  This seemed to me to be a bit of a
cop-out, especially in light of all the comments being posted on these
related RFEs.

Note that my proposal is limited to constructor methods in interfaces, but it
is related to the whole area of enhancing interface definitions.


Submitted On 09-APR-2002
schapel
What would be the advantage of specifying a constructor in
an interface? Constructors are not inherited, and are never
called polymorphically, so what would be the point?


Submitted On 14-MAY-2002
davidholmes
An example of the use for constructor declarations in an 
interface is in the collection classes. Implementations of 
the collection interfaces are supposed to provide a "copy 
constructor" that fills in the new collection with the 
contents of an existing one. At present this can only be 
suggested practice through documentation. If the interfaces 
could specify a constructor signature then all classes that 
implement that interface would have to have such a 
constructor.

There are similar examples for allowing static methods to 
be declared in an interface: the implementing class must 
define such as static method. Someone mentioned Singletons, 
well a singleton class is typically implemented with a 
static getInstance method - but you can't specify a 
Singleton interface, other than as a marker interface. What 
you'd like is a way to state that any class the implements 
Singleton has a static getInstance method. There is 
currently no way to do this.

I think allowing implementation of anything within an 
interface opens up too many problems.

As for allowing synchronized declarations that is a 
misunderstanding. If the intent is to specify the threading 
properties of a method then that specification belongs in 
the documentation. The use of synchronized is an 
implementation technique that provides a specific form of 
synchronisation - it is neither necessary nor sufficient in 
the general case.


Submitted On 06-JUN-2002
shrink_laureate
What this RFE really wants is metaclasses - class objects 
that can be referred to, passed around and called 
polymorphically.  Then a static interface and polymorphic 
constructors would all start to make sense.

Java will never have metaclasses, though.  It's far, far 
too big a change to the core language.  In terms of OO, 
Java has hit its limit. Sorry people, but this RFE will 
never happen.


Submitted On 24-JUN-2002
shrink_laureate
Note that some of the benefits of meta-classes can be 
obtained through the systematic use of singletons.  Try 
supporting the RFE for language-level singletons.

http://developer.java.sun.com/developer/bugParade/bugs/47017
98.html


Submitted On 27-JUN-2002
Dorceon
An interface definition can contain a nested class, which 
can contain a static method(and should probably be final 
with a private constructor). This means that the 
interface's static method name is lengthened by a few 
characters, but the implementation of a static method can 
be provided alongside the interface itself. There seems to 
be an issue in this discussoin with what people 
think 'static methods in interfaces' means--some 
think 'implementation follows interface' and some 
think 'abstract static'. The latter isn't really 
reasonable, since it wouldn't mesh with the concept of a 
static method.


Submitted On 08-AUG-2002
cakoose
Dorceon, I was just saying that Map.synchronizedMap() is
better than Collections.synchronizedMap().  If the designers
had wanted it to be polymorphic, they could have made
"synchronizedMap" a normal instance method.

I don't see how making it static and polymorphic helps at
all.  Compile-time resolution is the most you will need,
since you're going to specify the class name anyway.

Also, I wasn't suggesting final instance methods (unless I'm
getting my terms mixed up).  I was suggesting static methods
in interfaces so I can put my functions where I want (in the
Map interface instead of the Collections class).  I don't
intend to invoke them with an instance
(someMap.synchronizedMap) but with the interface name itself
(even though the compiler will use the reference type of the
variable for static methods in classes, this is frowned
upon).


Submitted On 08-AUG-2002
cakoose
An abstract interface doesn't make sense (as many people
have already said).  Take a look at the getVersion()
example.  Sure, it looks nice.  The thing is that everybody
who has given such examples never go past defining the
interface and class.  How would you go about using that? 
Eventually, you'd have to get the method name via
reflection.  The static method didn't even help.

The problem seems to be that people don't realize static
methods are more like C++ 'friend' functions than real
methods.  They are invoked by using the class name as a
qualifier (using an instance variable to invoke a static
method is frowned upon by the coding standards).

What I would like is a way to have normal static methods in
interfaces so that you could say something like
Map.synchronized() instead of
Collections.synchronizedMap().  This, as someone stated, can
be solved by using an inner class.  To make things easier,
the compiler could automatically make an inner class (see
"Util" example) and put all static methods in there.  The
compiler could also require that the interface name be
prefixed to invoke it (and not an instance).  To avoid name
clashes, the automatically generated inner class could be
called 'static' since the JVM doesn't use Java keywords. 
Though this would make a stack trace look a little weird on
older JVMs, it isn't impossible to decipher.

I want normal (non polymorphic) static methods simply
because they let you put code where you want to put it.


Submitted On 08-AUG-2002
Dorceon
Cakoose, you seems to be suggesting final instance methods, 
which in a C++ sense are like static methods; the problem 
seems to be with this RFE, which means a specific thing, and 
many people have their own interpretation of what it means, 
all different.
Of course there will be the usual argument over mutiple 
similarly named methods, but since your methods are non-
polymorphic, name ambiguities owuld be required to be 
reqolved by explicit casting, I'm sure. A more relevant point is 
the differences between interfaces and abstract classes. An 
interface is most often used to give the effect of function 
pointers(with the convenience that several related pointers 
can be grouped). The other typical usage is when several 
classes share methods with the same name and similar 
behaviour, they will often be factored into an Interface, 
whether or not a reference to the interface type is ever likely 
to be used, or useful.
(ie. a WritableByteChannel may be a useful type, but a Buffer 
probably isn't.)
Abstract classes tend to serve the roles of:
-Adapters for interfaces where some methods have a likely 
implementation, but most do not. (ie. AbstractAction)
-Situations where there are elements whose implentation is 
fixed (or at least unlikely to differ sufficiently that it would be 
worth allowing such differences), but other elements are 
implementation-dependant, and several possible 
implementations do exist. (ie. ByteBuffer)
Note that while for abstract classes with implementation-
dependant aspects, those aspects can be and often are 
protected, whereas this is not possible in an interface. Also, 
an abstract class can have instance fields, whereas an 
interface cannot; this heavily limits the number of 
implementation-independant things which can appear in the 
interface instance final method. In fact, the content of such 
methods is more or less limited to that of convenience 
methods; such methods are relegated to static methods of 
final uninstantiable classes in other places as well (ie. 
java.util.Arrays).
Also, your example does not make a great argument for your 
case, since it is one where polymorphism would be desirable. 
For example, while a HashMap would return a 
SynchronizedMap referring to itself, a HashTable or 
SynchronizedMap would want to save memory by returning 
itself, since it is already synchronized. (same for immutable, 
etc.) You could check for this, but I think you'll agree that 
<code>if(this instanceof SynchronizedMap)</code> is a bad 
line of code.


Submitted On 09-AUG-2002
Dorceon
Well, a final instance method and a static mathod that takes 
an instance of the class as its first parameter are pretty 
much the same as far as the compiler is concerned. (There's 
a small difference with introspection.) While you're adding 
implemented methods to an interface, you might as well be 
giving yourself the concise version.
In either event, the creation of a synchronized map is 
orthogonal to the concept of a map--putting that method in 
the Map class would be like putting a buffer() method in 
InputStream or OutputStream which returned a buffered 
stream wrapping the caller. You might save yourself some 
keystrokes with <code>new FileOutputStream(filename).buffer
()</code> vs. the current style, but buffering is a separate 
concern from a general stream, just as thread safety is a 
separate concern from collections in general. (I would 
personally prefer <code>Streams.buffer(new FileOutputStream
(filename))</code> to both the current system and the one 
proposed above.)


Submitted On 12-AUG-2002
cakoose
I didn't mean for the static method to take an instance of
the class as a parameter (C-style OO), though there's
nothing to stop you from doing it.  Static methods are
basically functions.  Sometimes, a static method needs
access to private class members and so must be defined in
the proper class.  Other times, such as with the
synchronizedMap implementation, the static method doesn't
need private member access and could be placed in the Map
interface to make for a cleaner and more obvious namespace.


Submitted On 12-AUG-2002
Dorceon
Are you saying that you didn't mean Map.synchronized() to 
take an instance of Map as a parameter, or that in general 
you didn't expect interface static methods to need to? 


Submitted On 06-SEP-2002
jim.willis
I have always wanted (and just recently asked for) a 
deletegate keyword.  This would allow a class to delegate all 
of an inteface implementation to a class variable.

public interface InterfaceA { 
  public methodA();
}
public class InterfaceAdapterA implements InterfaceA
{
  public methodA(){}
}
public class MyClass implements InterfaceA
{
  delegate InterfaceA myInterface;
  InterfaceA myInterface = new InterfaceAdapterA();
}

complies to 

public MyClass implements InterfaceA
{
   InterfaceA myInterface = new InterfaceAdapter();
   public void methodA(){ myInterface.methodA()};
}

With compiletime support, you can see more error checking 
and the automatic generation of passvars etc.  If you want to 
have a class override the Adapter implementation, the create 
an Anonymous Innerclass which calls the new 
implementation.

I have been using this model for years (as it very heavly 
documented in most java programming books), to reuse 
adapters.   It also provides a very clean way to extend 
wrappers and interfaces, suchas adding features to 
java.sql.Connection.  I can essentially extends the underlying 
implementation without writing a series of wrapper 
methods.  Also if interface Connection should  change, I only 
have to recompile.


Submitted On 27-SEP-2002
steveftoth
to jimWilis:
Unfortunatly your delegate keyword will not work in java
because of the way that java resolves 2 interfaces with the
same method signature.
interface a {
void go();
}
interface b {
void go();
}
class c implements a , b {
public void go() {
//called regarless of wether calling code thinks it has
// an a reference or a b reference.
} }
so basically, if you have two delegates then which is
called?  or what if you delegate 'a' and then implement 'b'
in the class? (I guess the second example is a little
simpler as the classes implementation probably should be called)


Submitted On 19-NOV-2002
Falric
to steveftoth:
that is easily resolvable. The compiler should simply
require class c to explicitly define the go method in that
situation (perhaps calling go() on two delegate classes). If
your design is good there should be no conflict in the same
method implementation serving both interfaces.

to jim.willis:
Btw, there is already at least 1 rfe on this already. See 
4388580. Add your vote!


Submitted On 14-FEB-2003
Parkway
I almost buy the inner class workaround, except it doesn't
quite work as I expect:

interface in {
  static class Factory implements in {
    static in createInstance() {
      return new test();
    }
  }
}

public class test implements in {
  public static void main(String[] args) {
    Factory.createInstance();
  }
}

test.java:11: Undefined variable or class name: Factory
    Factory.createInstance();
    ^
1 error

BTW, if you compile Dialog d = constructDialog; d.show(); in
1.1 or later it will not run on 1.0.2, but (Window)d.show()
will!


Submitted On 19-FEB-2003
schapel
There's a trivial workaround for the static nested class 
workaround not working as you expect. Change it from a 
nested class to a top-level class. Just move the class 
definition to outside the interface, and there you go!!!


Submitted On 22-FEB-2003
verdy_p
Finally to terminate the debate about the semantics of static 
fields and methods in interfaces, they would be compiled 
simply as part of the $default class implicitly built.
Note that because the compiler would create a nested 
$default class as a companion of the declared interface, all 
methods in the interface that don't have an explicit default 
implementation become abstract. As static methods cannot 
be abstract, this means that static methods declared in 
interface would *require* an implementation that can be 
inserted in the $default nested class that the compiler would 
build.


Submitted On 22-FEB-2003
verdy_p
Another interesting way to disambiguate methods inherited 
from multiple interfaces, for the above example:
class C extends I1 implements I1, I2 {
  void other_methods() { bar(); }
}
This would compile as:
class C extends I1.$default implements I1, I2 {
  void other_methods() { bar(); }
}
Here there is no conflict because class inheritance from the 
default implementation in only one interface is explicitly 
specified and takes precedence to the default unspecified 
implementations provided by the conflicting interface.


Submitted On 22-FEB-2003
verdy_p
Vote against constructors in interfaces. Interfaces are made 
to use already constructed instances of any class that 
implement it. So each time we need an interfaced object, we 
don't instantiate the interface but a class that implements it.
So basically, there is absolutely no need of any static method 
in an interface.
Polymorphic static methods is also a crazy thing: how would 
you call them without referencing them through an actual 
instance ? If you need to provide an instance to disambiguate 
the implementation, then the method is not static.

It seems that all demands and examples are related to 
providing a default implementation for interfaces, that may or 
may not be overriden in classes implementing them.

But the problem is multiple inheritance of interfaces: would 
this allow developers to deviate the concept of interfaces 
into actual classes ?

If static methods and members were added to interfaces, 
then we should not tolerate polymorphism: these default 
implementations should really become final, and multiple 
inheritance of interfaces that define the same method would 
need to be forbidden (because the implementation would be 
ambiguous). This would add restrictions on interfaces that 
would now be incompatible for implementation in actual 
classes, and then would require defining multiple interfaces 
with or without the conflicting static methods...

Let's just keep the idea of default implementations of non 
static methods: an interface could define a default 
implementation class that implicitly implement it.

So any implementation found in an interface declaration would 
compile into two separate elements: a clean interface, and a 
friend class that contain the default implementations. This 
way other classes would be free to implement or not 
implement the method. If not implementing it, its method 
would point to another class (the default class defined by the 
interface). If there is a conflict between multiple interfaces, 
the class implementing them would be required to reimplement 
the conflicting method.

Example 1:

interface I {
  void method() { foo(); }
}

would compile as:
interface I {
  void method();
  class $default implements I {
     void method() { foo(); }
  }
}

Then when declaring:
class C implements I {
  void other_methods() { bar(); }
}
the compiler would generate implicitly:
class C implements I {
  void other_methods() { bar(); }
  void method() { I.$default.method(); }
}

Example 2:

interface I1 {
  void method() { foo1(); }
}
interface I2 {
  void method() { foo2(); }
}

would compile as:
interface I1 {
  void method();
  class $default implements I1 {
     void method() { foo1(); }
  }
}
interface I2 {
  void method();
  class $default implements I2 {
     void method() { foo2(); }
  }
}

Then when declaring:
class C implements I1, I2 {
  void other_methods() { bar(); }
  void method() { foo3(); }
}
the compiler would not signal the conflict between 
I1.$default.method() and I2.$default.method(), because we 
have an explicit implementation to solve that conflict.

But the above class should refuse to compile if the conflicting 
method() from both interfaces was not explicitly overriden 
with a non default implementation.
If one wants to disambiguate which method to call, it could 
use in class C:
  void method() { I1.method(); }
or
  void method() { I2.method(); }
which would compile as:
  void method() { I1.$default.method(); }
or
  void method() { I2.$default.method(); }

This way, interfaces stay clean in the JVM, the work is 
actually performed by the compiler that can generate relaying 
implementations in classes (only when there's no conflict of 
inheritance).

With this concept, we don't need any static method in 
classes, and compiles interfaces stay compatible with the 
previous JVMs.


Submitted On 28-MAR-2003
Simon902100
Excuse me, that previous post was in reference to abstract 
*static* methods.  Duh.


Submitted On 28-MAR-2003
Simon902100
While I must admit I don't know a great deal about the 
intracacies of Java compilation, I think allowing abstract 
methods could be quite useful.  For example, say we have a 
Car type.  Every car has a set of possible colors and we want 
to assume that, barring any additional information, a given car 
is available in N certain colors, say Red, White, and Blue.  The 
Car type would naturally be an abstract class or interface 
that would be extended or implemented by another class, say 
a 1995 Honda Accord.  It just so happens that a 1995 Honda 
Accord was available in colors other than Red, White, and 
Blue.  That is, the *class* of 1995  Honda Accord had this 
attribute.  A specific instatiation of this class would obviously 
have only one color (for most modest individuals ;) ).  Given 
any particular class derived from the abstract Car class (or 
interface), I want to determine what colors are available.  
Since the available colors are a property of the class, the 
function to get these properties should be of the class as 
well.  Furthermore, all Car classes should be given the option 
of overriding this function.  Are there not at least a 
substantial enough applications similar to this to warrant the 
ability of having an elegant solution to this problem?  


Submitted On 01-APR-2003
schapel
For a method call to be polymorphic, you need to call it on
an object. Therefore, the method must be non-static. If you
make the method that returns the available colors static, it
cannot be polymorphic, and therefore cannot exhibit the
desired behavior. The solution is trivial: make the method
non-static!


Submitted On 25-APR-2003
jdcjdc
This is a phenomenally stupid idea. A lot of people don't
like code inside interfaces; they also don't like static
junk like fields and methods in them. Java interfaces are
close to perfect, so please don't mess with them.

Besides, adding this feature would cause immense confusion
-- static methods are called via classes. That is, there is
no inheritance model associated with static methods. Whereas
interface methods are virtual and can be completely separate
from the classes that create them.


Submitted On 04-JUN-2003
johannesreich
Just an example in favour of static methods in an interface:

A ClientFamily contains a collection of homogenous Clients of 
one class type and provides each with a reference of part of 
its state (e.g. a very large message). The format of the state 
object is Client specific (e.g. XML or EDI format), however the 
type of the Client-class can vary. So only the Client knows 
the format to which the byte-blob should be transformed. It 
seems natural to me, that the ClientFamily, whose 
responsibility is just to keep the client state, could ask the 
Client-class for a conversion into the state format, the client 
object needs later on.


Submitted On 14-JUL-2003
dgkimpton
Parkway :

simple fix - 

interface in {
  static class Factory implements in {
    static in createInstance() {
      return new test();
    }
  }
}

public class test implements in {
  public static void main(String[] args) {
    in.Factory.createInstance();
  }
}


This inner class workaround is superb.  It nicely ties
utility classes into the interfaces on which they work.  It
would be nice if in an implementation of an interface we
didn't have to specify the interface name every time we
refer to inner classes but this is not such a huge issue.

As to the idea of polymorphic static methods - whuh??? That
really makes no sense at all.

Constructor signatures in interfaces is an idea with alot of
merit.  It should also be easy to implement.  It seems it
would be most usefull in the case of reflection - i.e. a
forName method would then be able to take a parameter list...


Submitted On 07-OCT-2003
schapel
I don't see how putting a constructor signature in an
interface would help anything but reflection. I suppose all
classes that implement the interface would have to implement
all constructors in the interface. But what if I am writing
my own private class and I can guarantee that some
constructors will never be called. I still have to write
them anyway? That sounds like it's just unnecessary work.

I don't understand the comment about forName being able to
take a parameter list. Maybe you could explain.

If a change to Java has merit, you should be able to post
some Java code you've written, a concise and understandable
explanation of the new feature, and the Java code rewritten
using the new feature along with an explanation of why the
new code is better in some way. I've never seen such an
example for any of the features proposed in this entire RFE.
Could someone please provide such an example? Just a very
simple example would do more for convincing someone the
change has merit than all the above hand-waving!


Submitted On 20-OCT-2003
rxjunk
Interfaces being (in essence) a contract by which the 
implementers must abide should have the ability to specify a 
set of abstract static methods and abstract constructors. 
Having concrete static methods or indicating that methods 
are to be final, protected, package-private, or synchronized 
seems to break with the "what-not-how" spirit of interfaces.

In particular, my recent project included an interface like this:
public interface Codec
{
	public abstract Object decode(DataInput in) throws 
IOException;
	public abstract void encode(Object obj, DataOutput 
out) throws IOException;
}

Each implementation dealt with a different class; it would 
have been nice to specify:

public interface Codec
{
	public abstract Object decode(DataInput in) throws 
IOException;
	public abstract void encode(Object obj, DataOutput 
out) throws IOException;
	public abstract static Class getType();
}

This way each implementing class could answer, independent 
of any instance, what data type it encodes/decodes.


Submitted On 04-JAN-2004
capmember1
In short:

1. Static methods are polymorphic if you have type 
parameters and an object for each class (containing those
static methods), so what?

2. Many classes are using static factory methods (hiding
there constructors (look into the platform!). It would be of
big value to specify  these methods in a contract (the
alternative of a prototype object is not nice and not widely
used yet).

3. Look a a pseudo-symmetric method in an Interface XY like

double distanceTo (Point to)

The contract should be:    a.distanceTo(b) == b.distance(a)
But this contract could easly be broken by different
implementations.

A realy symmetric static method like

    double distance(Point a, Point b)

will be much cleaner and will stick to the contract.




Submitted On 29-JAN-2004
gbishop
Schapel asks a question that deserves an answer: 
WHY WHY WHY?

I have had a need for this that I think everyone can 
understand.  I have 2 classes with identical static 
methods.  These classes are not inheriting from each 
other, but from a common base class that has none of 
the static methods these classes have.

Let's say one file is for DB2 and the other is for Oracle, 
and the method is something like public static User 
getUser(username, password){...} that will handle 
getting the connection, closing the connection, etc.

At run time I want to factory up one class or the other.  
But we have a problem!  We can't do that because the 
factory must return a class or an interface.  Neither will 
do the job we need done.

We can't factory up a class because the implementers 
want to call something like getMyClass().staticMethod
(), but the getMyClass returns what?  An interface?  It 
can't because the method in question is static.  A 
class?  It can't because even if we created a class that 
both A and B inherited from it can't have _abstract_ 
static methods.  Its methods will be called at run time 
because as has been pointed out, the method called 
is determined at compile time.

Now of course we COULD make the classes non-
static and create silly object references to them, but 
WHY?  Why can't I simply factory up a thing that will be 
properly dispatched to a class method of the 
appropriate class at run time?

Before you give me a glib answer that dispatch is the 
problem, consider that you CAN do this if you do 
getClassFor name and use introspection to call the 
static methods of the class you loaded.  So it CAN 
work.  Just not with interfaces at the present time 
which is the subject of this RFE.

My solution would be to require all static methods in 
interfaces to be declared as abstract which would 
mean that you HAVE to provide a implementation in 
child classes, and that the dispatch will be done at run 
time not compile time to some class method of a 
class that implements the interface.

There are problems with this implementation idea, 
including inheritance and allowing a change to the 
meaning of certain Java key words, but the capability is 
a real need.

Enicholas is has points but is wrong on two accounts: 
1. static final methods ARE allowed in Java, such 
methods can not be sub classed, and 2. abstract static 
method is exactly what is needed, a method that must 
be implemented by an interface's (or potentially a 
class's) children that is not tied to a runtime instance 
of the class.

Leolore brought up an interesting point in that he 
states that “Even if the interface could not declare the 
method as static, if the class could actually implement 
it as static, it would be better than it is now."  This 
course runs into the dispatch issue, but I think a new 
Dispatch mechanism that functions as I outlined it 
instead of like the current static method dispatch 
method for classes could be made to work.

Steveftoth states that "This idea will not work.  For the 
reason that static is not polymorphic.  Since all static 
calls are resolved at compile time not at runtime, there 
will be massive confusion on which method to call."  
There is already confusion, and the behavior we are 
discussing is MORE intuitive than the current compile 
time dispatch method that is almost NEVER what the 
programmer intended to do.

I do not think proper implementation of this feature 
would even break working code.  It might even fix some 
existing bugs.  The change would have to be well 
documented and explained, but I think pointed headed 
PhD's could figure it out just fine.


Submitted On 25-FEB-2004
sfriedberg
As with most of the other commentors (since 1997?!),  I have run into situations where allowing an interface
to have static methods would simplify a design and remove unnecessary class instantiation.  In fact, I
have a set of functionally related, but not identical, classes.  Those which functionally do not require
static methods (for initialization or whatever) are handled simply with an interface. Those which DO
require static methods require more code just to get a  handle on a static method, and don't allow me to write
the functionally related sections in an obviously parallel fashion.  This is not only annoying; it isn't good for future maintenance.


Submitted On 17-MAR-2004
Clive.Brettingham-Moore
It seems the problem here is too many features not too few:
For example, in the (mercifully ) dead issue of synchronised
method signatures in interfaces the actual problem may be
that synchronised methods don't actually exist - this
compiler is simply nice enough to emulate this feaure by
automatically generating a synchronized (this) block around
the body. Useful, but gives people quite the wrong idea
about what is actually happening.

Similarly with static  members- the complier is nice enough
to resolve references to superclass static members
automatically - giving people the (very false) impression of
 [for want of a better word] "virtual" static members, and
creating a desire to utilise a feature (via interfaces) 
that doesn't actually exist.

Interfaces are a [runtime] role definition/declaration
mechanism - and only and instance can actually have a role
in this sense - static methods are missing the point. (this
also relates to constructors - interfaces are about  finshed
instances; factories were a good idea long before java).
Final fields for interfaces are already a big concession to
convienience (again, at a guess, more compiler illusion than
reality).

RE: delegate - design, people!
If an object inplements an interface it should logically fit
into the role. If your class has too many roles, you should
ask - is it really a <...>. If not, consider real delgation:
use a references to inner classes that fit each role more
neatly. Neadlessly passing a reference to a "class of all
trades" is simply bad design.

Java with inner classes comes very close to full multiple
inheritence in direct effect  and vastly exceeds it in more
imaginative applications. If you've run out of rope, maybe
you are going in the wrong direction.



Submitted On 21-MAR-2004
schapel
gbishop: It seems that all you have to do it make the 
static method in your example non-static and define an 
interface with that method. It really is as simple as that. 
That will make the method call polymorphic, and the 
appropriate classes' method will be called.

If I have missed the point of your example, please 
somewhere post the code you have written in Java, a 
description of the feature you would like to see 
implemented, the code rewritten to make use of your 
new feature, and then an explanation of why the new 
code is in some way better. I still have yet to see this, 
and until I do I cannot see why static methods in 
interfaces would be of any help.


Submitted On 07-APR-2004
xuhaoqing
Given an interface:

interface MyInterface {
	public static void foo();
}

and a class implementing it:

class MyClass1 implements MyInterface {
	public static void foo() {...}
}

and another class:

class MyClass2 implements MyInterface {
	public static void foo() {...}
}

and the following code:

for (MyInterface one : theList) {
	one.foo();
}

The above code just can not work, because the compiler sees
object "one" as class type MyInterface, therefore it will
try to generate code to call MyInterface.foo(), which is
abstract.

So how to let the complier generate proper code according to
the real class type of an object? Consider this:

class F {
	public static foo() {...}
}

class S extends F {
	public static foo() {...}
}

F obj = new S();
obj.foo();

Current compiler will generate F.foo() for the example. If
it could see obj is actually an S and would generate S.foo()
(Just like how it treats instant method), interface would
have no reason not to have static methods.





Submitted On 10-APR-2004
pmuurray@bigpond.com
The reason for putting static methods in interfaces is 
to allow ne to call a method without putting a class 
name in front of it by importing an interface.

This is bad style for the same reason that importing 
interfaces with constants in them is bad style.

Java 1.5 fixes this by allowing you to do a static import, 
so I personally think this RFE should be closed.


Submitted On 13-APR-2004
ccerberus
This RFE should be closed as "Will Not Be Fixed" 
because it's patently absurd.  The people who are 
requesting it, having reviewed their comments, 
basically either don't understand the proper use of the 
Java language or are just useless at code design.  I 
mean, "HELLO, do you actually understand what an 
Interface is FOR?"

I support the views of the so-called naysayers up 
above.  Their reasoning is much stronger.  If NOTHING 
else, no matter how you slice it, this ends up 
resembling multiple inheritance.

This kind of bug is exactly why we should have 3 
votes "against" bugs as well as "for" them.

Sun, please close this goofy thing.


Submitted On 03-MAY-2004
hlovatt
This idea of specifying static methods and constructors is
only relevant if you have something like NextGen:

http://www.cs.rice.edu/~javaplt/nextgen/doc/

which is an enhancment to generics that allows you to access
static methods and constructors.  In Java 1.5 you have to
manually provide hooks to static methods, static fields, and
constructors via instance methods.

The NextGen compiler works by writting a new interface and
modifying your class so that it implements this new
interface. The new interface contains instance methods that
are to call the static methods defined in the original
interface and your class is modified to have these extra
instance methods added.

The NextGen compiler does something similar with
constructors, but uses an abstract class and modifies your
class to extend the abstract class.

The NextGen system  doesn't use the static keyword in
interfaces, instead it uses an extra 'where' clause which is
used a bit like 'implements'. The NextGen system seems to
have heavily influenced the C# designers, since their
generics proposal is very similar to NextGen.

One of the designers of NextGen is Guy Steel who works for Sun.


Submitted On 26-MAY-2004
YoGee
How can this "Bug" have 146 votes!? It's ridiculous.  Perhaps there should be some sort of prerequisite for voting, like having a basic understanding of the Java language ...


Submitted On 11-JUN-2004
Sylvia_Carmen
So, six and a half years later, we're still waiting.

I'm still finding situations where static class methods would make things neater. Not all interfaces are used for polymorphism and no one has a God given right to pontificate on the 'correct'  way to use an element of the language.


Submitted On 23-JUN-2004
Clive.Brettingham-Moore
Counts to ten  very, very  slowly.
I don't know whick language you guys think you're programming in, but I thought we were talking about Java.

I have the feeling I'm wasting my breath, but here goes

Static methods are implicitly final (ie CANNOT BE OVERIDDEN), and are called, as one might expect, in a completely different way to exposed instance methods - the not called using an instance, but on a completely diferent object, the class object.

Invocation of a static method via a reference simply doesn't  happen, it can't. It is invoked on the type of the variable, not the object (the object's class isn't even known at compile time).
Accessing static mehods (or fields, but less so) though an object reference does not represent what actually happens; it is bad programming practice period. 
(And it's official, point 10.2 of the java code conventions:
"Avoid using an object to access a class (static) variable or method. Use a class name instead.")
http://java.sun.com/docs/codeconv/html/CodeConventions.doc9.html#587

If implementations differ in their implementation of a method then it is not logically a static member of the interface.

There is only one usage where static methods might logically relate to an interface - utility methods that apply to all objects with the interface. These can be encapsulated in a utility class.

(see my previous comment about inner classes and modularisation)


Submitted On 24-JUN-2004
Clive.Brettingham-Moore
speak in haste.....

I was completely wrong about the implicit finality of static methods (it was, apparently, implicit only for me lol)
Static method resolution occurs at runtime with a search of the class hierachy. (I can see why although there )

Nit picking is on my side, these methods are not overridden, they are hidden, which has important functional differences... 

My agument stands:
 invocation (of static methods)  is still undertaken solely with reference to the declared type, not the object type,.

.. and you still shouldn't be using a variable to invoke a static method. 


Submitted On 14-JUL-2004
schapel
xuhaoqing: Just remove the "static" from your method declarations, and your code works exactly the way you want. There is no need for any additional Java language features to get the desired results.

If anyone still thinks they have code that would benefit from any of the features listed in this bug, please post it and we'll show you how to easily get it to work in current Java. We're not pontificating the correct way to write Java, just showing that there's an easy way to get the results you want in the Java language as it exists today.


Submitted On 05-AUG-2004
bryce_dorman
This is something I have come across many times when trying to make generic code.

Turning this in multiple inheritance and having concrete methods in interfaces would be a serious mistake as that would just be a class.

However, the ability to be both static and abstract would allow you to have much better factory-like classes for example.



Submitted On 06-AUG-2004
schapel
> However, the ability to be both static and abstract
> would allow you to have much better factory-like
> classes for example.

Can you explain this statement? If you want a method to be abstract, why doesn't it suffice to simply make it not static? What is the advantage to making the method static rather than non-static? In all this discussion, I've never seen one word as to *why* this is desirable.


Submitted On 06-AUG-2004
bryce_dorman
Working around it is not the issue.  At times it is important to be able to define an interface and yet to be able to have a class definition . 


Submitted On 23-AUG-2004
axel.g
well, I think the issue many people have, is that they 'feel' that a static method should belong to the class and not to the instance.
Like with variables; static variables belong to the class and member variables to the instance.
That it's more an issue about how the method is called is not in their scope.
So maybe this is just a problem of overlapping terms.
'Static' indicates another way of finding the right method instead of using runtime binding. So I'd advise to choose the type of binding and then put in the keyword, or not... :)


Submitted On 23-AUG-2004
axel.g
just a thought after reading the evaluation again (which I think missed the original point): It would maybe be nice/useful to put annotations into the interfaces to enforce some more elaborated contracts. That would force the implementing classes to have the specified annotations. I'm aware this would put annotations into the signature, so I don't know if this would be feasible. But I think it would add a lot to expressiveness :)


Submitted On 08-SEP-2004
headw01
Egad...  If you want static methods in your interfaces, you can already do it (sort of ;-) )...

public interface MyInterface {
    public static final MyStaticMethods STATICS = new MyStaticMethods();

    public int getInt1();
    public int getInt2();
    
    public final static class MyStaticMethods {

        private MyStaticMethods() {}

        public static void message(String message) {
            System.out.println(message);
        }

        public int add(MyInterface myInterface) {
            int sum = myInterface.getInt1() + myInterface.getInt2();
            message("Sum : " + sum);
            return sum;
        }
    }
}

public class MyClass implements MyInterface {

    public int getInt1() {
        return 17;
    }
    public int getInt2() {
        return 25;
    }   

    public void evaluate() {
        STATICS.add(this);
    }   

    public static void main(String [] args) {
        MyClass cls = new MyClass();

        MyInterface.STATICS.message("Message 1");
        MyStaticMethods.message("Message 2");

        System.out.println("evaluate ...");
        cls.evaluate();

        System.out.println("add ...");
        MyInterface.STATICS.add(cls);
    }
}


Submitted On 10-SEP-2004
renkrad
>Working around it is not the issue.  At times it is important to >be able to define an interface and yet to be able to have a >class definition . 

Then an abstract class should be used.


Submitted On 10-SEP-2004
renkrad
Placing static methods in an interface it's against the filosophy of the interfaces. It defines caracteristics not rules.

If it's necessary to define a static methods, or regular methods with a 'standart' definition, then the use of an abstract class should be considered.


Submitted On 29-APR-2005
schapel
"At times it is important to be able to define an interface and yet to be able to have a class definition."

I ask yet again... why?


Submitted On 23-JUN-2005
my_stupid_screen_name
As interfaces in Java are often used to define constants it would sometimes be nice to have a set of hepler methods directly accessible from the same interface. Here is a simple example:

interface Message
{
    int TYPE_FOO = 1;
    // ...
    int TYPE_BAR = 7;

    int getType();

    boolean isValidType( int type )
    {
        return type >= TYPE_FOO && type <= TYPE_BAR;
    }

    Message create( int type )
    {
        MessageFactory.getInstance().createMessage( type );
    }
}

Methods with a body in an interface should be implicitly static and thus final, similar to the rules that already apply to fields in interfaces. I don't see any conflics with existing rules for such a extension.


Submitted On 28-JUL-2005
schapel
You're using the Constant Interface Antipattern to demonstrate the usefulness of static methods in interfaces!? Ugh! Put the helper methods in a class instead, and use enums for the values. You can use static imports if you don't want to spell out the constants fully.


Submitted On 06-AUG-2005
JessHolle
I don't see what static methods really buy here.  Now allowing default implementations of *instance* methods in interfaces is long overdue -- but Sun has officially stated that this is never going to happen...


Submitted On 10-AUG-2005
dubwai
It seems reasonable to allow static final methods in interfaces.  static final member variables are allowed and static inner classes are allowed.  Why not static methods.  I don't see the harm in that.

However, there are some goofy ideas here.  abstract static methods make no sense.  I think you must misunderstand how static methods are bound.  Default implementations for instance methods defeats the whole point of interfaces.  We might as well allow multiple inheritance from classes and eliminate interfaces.


Submitted On 18-NOV-2005
Mike-Skells
I support the concept of mixin classes. This i some way towards that and in a more detailed analysis and adoption of mixins whoudl allow this.

Also interfaces need a way to evolve. Ther neeed ts be a way to add methods to an interface /mixin to that interfaces can be the predominant programming type, rather that some interfcae and some base class, as the base classes evolve and leave the interfaces behind 



Submitted On 17-DEC-2005
malcolmmc
It's clear to me it's not meaningful to declare bare signatures for static method in Interfaces, becaue the interface would not know which of, potentially, many implementations in different classes was relevant when you made a static call. Actual method implementations in interface makes slightly more sense, but the problem is that you could easilly have a class which implemented more than one interface with different implementations for the same static method signature, which is the very reason why muliple parent classes are not allowed.

I think a case might be made for something like an interface for classes rather than objects. A contract which comitted a class to providing a set of static fields, methods and constructors. A class of classes, if you like. However it wouldn't be an interface as we know it. It would be classes that where instances of it, not objects. You could see it as an extension of the Class class.


Submitted On 07-APR-2006
Here is a possible alternative solution that may meet the needs of those who want to add static methods while minimizing the tweaking of the Java language:  allow the methods in an interface to be implemented with static methods if the implementing class chooses.
I suggest that whether a method is a class or object method is a property of its implementation, not of its interface.


Submitted On 11-APR-2006
schapel
"I suggest that whether a method is a class or object method is a property of its implementation, not of its interface."

This "solution" falls apart when you realize that class methods and instance methods are implemented and called differently by the JVM. They're two entirely different beasts at the JVM level, and they're incompatible. Let's say you make a call to an interface method using the class method syntax (by giving the class name instead of an object), but the implementation is an object method which expects an object. There is no object, so how can the method be executed? Should it fail at runtime with a NullPointerException? Ugh!

Instead of allowing class implementations of interface methods, just declare implementations of interface methods as object methods, and don't use the object if it's not needed. This works with all JVMs and avoids the problems of not having an expected object with the proposed "solution".


Submitted On 08-JUL-2007
Wow! What a soap opera! I got out the popcorn when KizubM stormed out of the room, only to come back ex-business-partner schapel.

SDN members, let some good come of poor schapel's preaching for 7 years. After analyzing over 10 years of posts, it would seem that the reasons developers wants static interface methods are:

1. To use a methodset without including some extra characters. As pmurray says, use static imports, and as schapel says, use helper classes, declared either inside or outside the interface if need be. Deal with the extra characters.

2. Static polymorphism. I love this. Literally translated: 'don't change but do change the form'. The version example given by davidtribble _is_ admittedly potentially useful, but only with reflection. The signature in the interface:

interface I {
    static int ver();
}

Can be interpreted simply as as declaration:

"for any class A implementing I, if you get an object of class A, get its class with .getClass() and then attempt to access method ver() by reflection in the returned Class, the access is guaranteed not to fail"

There are other ways of doing this. Admittedly, polling and/or catching 'not found' exceptions while using reflection isn't exactly eye candy, but there's how you do it.

3. Because we should be able to declare an interface method as static if we durn wehl went tu. Yes, it _is_ nice in some cases not to have to create an object.  schapel has been pleading for an actual case of this; here’s a gross simplification of one I ran into:

interface ControlSystem {
     ...
     bool is_output_stable( double[] inputs );
}

class BIIIG_FIR_Control_System implements ControlSystem {
    double data[100000];
    ...
    static bool is_output_stable( double[] inputs ) {
        for( int i = 0; i < inputs.length; i++ )
            if( Double.isInfinite( inputs[i] ) )
                return false;
        return true;
    }
}

This, of course, is not allowed, and so instead of:

BIIIG_FIR_Control_System.is_output_stable( x ),

we either recode or use:

BIIIG_FIR_Control_System BFCS; // Memory (Yum!)
BFCS.is_output_stable( x );

But, acknowledging this convenience, schapel _is_ right. There are a million other ways of recoding this that, although not _as_ pretty, get the job done.

The bottom line is that schapel and Clive.Brettingham-Moore are right. There is no good case for putting in this feature to kibosh backwards-compatibility, totally retool the linker, and further pollute the nice, clean, simple interface that we've all come to know and love. (I've been coding in C++ recently again: peeeee-yuu without interfaces!)

So as pmurray and ccerberus suggest, let us move our votes to features that have no simple workaround. Let 4093687 die: an old man safe in his bed. And let good schapel and true, one of the few souls that actually seems to understand how compilers _work_, save his strength for bigger battles elsewhere.

- vsyonid


Submitted On 28-OCT-2008
fzenner
To me static methods in interfaces are in some ways similar to enums. Not entirely necessary, but enormously instrumental in de-cluttering code. 


Submitted On 10-FEB-2009
Clive.Brettingham-Moore and scapel have some good points.  Nonetheless syntactically it would be prettier to allow this dispatch mechanism.  Otherwise you end up with a mess.  Code should be pretty. 


Submitted On 10-FEB-2009
schapel, sorry typo, no offence intended.


Submitted On 12-JUN-2009
schapel
"enormously instrumental in de-cluttering code."
"syntactically it would be prettier to allow this dispatch mechanism.  Otherwise you end up with a mess.  Code should be pretty. "

Could anyone give a short but complete example of current Java code that is cluttered or messy, and an example of how the same code could be written in a de-cluttered or pretty way using "static methods in interfaces"? I have yet to see how this feature would deliver the described benefits.


Submitted On 11-JUL-2009
daniel_l_smith
What a mess of misunderstandings and misconceptions.  I'm for the change (specifically, the change originally requested: that a static method be allowed to be defined and implemented in the body of an interface declaration).

Four points:

1) Since interfaces can have static fields and static classes, the language is going out of its way to prohibit static methods.  As java.util.Collections.emptyList() demonstrates, the distinction between a static field and method is not great, and a slight change may dictate refactoring from one to the other.  (Imagine if java.util.Collections.EMPTY_LIST had been defined, quite naturally, in java.util.List instead.)

2) It's not the case that interface declarations contain no code, and are thus fundamentally "simple."  Every static field is initialized with an arbitrary expression, which is compiled into the interface's class file.

3) I'm no expert on the JVM but I don't buy the idea that we're constrained by it.  For one thing, it's been demonstrated (way, way above) that static methods in an interface can be compiled to static methods in a generated helper class.  For another, there's nothing obvious about the JVM "invokestatic" command that prevents it from calling a method in an interface (which is just a class file with an "interface" flag set).  For another, backwards-compatibility concerns are silly: older VMs won't run code that has been compiled with a "-source 1.5" flag anyway (for example).

4) A lot of demands for a use case.  What's wrong the example of java.util.Collections, which is a bunch of static methods that belong in java.util.Collection?  The class in which a static thing is defined is just a namespace (a name prefixing global data or functions), so of course there's not going to be any more persuasive argument than "this is the namespace that is most natural for me to use, but I can't use it."  But I don't see why that argument isn't persuasive enough.  (For what it's worth, I very frequently find myself defining "Util" classes for static fields/methods that really belong in an interface that defines the principal type the Util class operates on.)


Submitted On 21-JUL-2009
MiguelM
For anyone interested in a use case, I'll be posting one in a week or so. (Please don't close this until then.)


Submitted On 21-JUL-2009
MiguelM
For anyone interested in a use case, I'll be posting one in a week or so. (Please don't close this until then.)


Submitted On 22-JUL-2009
MiguelM
So here's my use case for abstract static methods. This applies more to abstract classes than interfaces, but they would be useful in interfaces for the same reason.

My current project uses Google Protocol Buffers to transmit data over the network. So I have an abstract class that looks like this:

import com.google.protobuf.GeneratedMessage;

abstract public class AbstractTransceiver<M extends GeneratedMessage>
{
  public AbstractTransceiver(SomeClass initializer) { ... }
  public void send(M msg) {
    // This one is easy to write
    sendBuffer(msg.toByteArray());
  }

  public M receive(byte[ ] buffer) {
    M msg = convert(buffer); // See convert(), below
    return msg;
  }

  public void sendBuffer(byte[ ] buffer) { ... }

  abstract protected M convert(byte[ ] buffer);
}

The send method is easy to implement, but I can't fully implement the receive method because protocol buffers use a static method to do the converting. There's nothing wrong with their design, either. The method is static because I don't have an instance from which to call it. So every subclass of AbstractTransceiver (there are many) looks something like this:

public class ReplyTransceiver extends AbstractTransceiver<MyReply> {

  public ReplyTransceiver(SomeClass initializer) {
    super(initializer);
  }

  @Override protected MyReply convert(byte[ ] buffer) {
    return MyReply.parseFrom(buffer);    // call a static method
  }
}

MyReply is a generated class that extends GeneratedMessage, so it has the toByteArray() method that I need in the send() method. But the receive method needs to create an instance of MyReply from a static method (parseFrom()), which I can't implement in the base class. But if Java would give us abstract static methods, then the GeneratedMessage class would be able to declare this:

  abstract static GeneratedMessage parseFrom(byte[ ] buffer);

or, better yet, they could add a type parameter to the base class, making it GeneratedMessage<M>. Then they could declare this:

  abstract static M parseFrom(byte[ ] buffer);

Then any class that extended it would have to implement this method (which it would do anyway), and the receive() method wouldn't need to call any abstract method. Instead, it would look like this:

  public M receive(byte[ ] buffer) {
    M msg = M.parseFrom(buffer);    // This was M msg=convert(buffer);
    Return msg;
  }

So my AbstractTransceiver class could become a concrete Transceiver class. I wouldn't even need to subclass it. I could just declare a new instance like this:

  Transceiver<MyReply> transceiver = new Transceiver<MyReply>(initializer);

This is much cleaner than the ReplyTransceiver class above.

The method to look at is here the static parseFrom() method. It's called from class M, and it returns an instance of M. I've often needed to write or use methods like these, on very different projects, and these methods are necessarily static. They are essentially factory methods in non-factory classes. In this case, if GeneratedMessage were a concrete class, this factory method could be written as a constructor, but that wouldn't help me here. (I can't specify an abstract constructor either.) This is one kind of method that would benefit from the freedom to declare abstract static methods, but I'm sure there are others. Sometimes, as in this case, they would be abstract methods of concrete classes, but other times they would belong in interfaces. Both types should be supported by Java.


Submitted On 22-JUL-2009
MiguelM
My last post makes my case, but I should make two extra points. First, some people have interpreted this RFE as a call for fully-implemented static methods in interfaces. While I can see the value of this idea, it's a different question. I don't have an answer, although I should point out that it doesn't help me in this use case. In this case, the static method would go into an abstract class, not an interface, so if it could be written, it would already exist. In fact, the static parseFrom(byte[ ] method looks like this:

  public static MyReply parseFrom(byte[] data)
    throws com.google.protobuf.InvalidProtocolBufferException {
    return newBuilder().mergeFrom(data).buildParsed();
  }

The newBuilder() method that it calls is also static, and all it does is call a constructor for a MyReply.Builder class. This can't be written in the base class. 

Second, some people have pointed out that, if we allow abstract static methods, we would be free to implement them, but we wouldn't have any way to override them (without further changes to the Java language). While this is a valid point, it doesn't bother me. In this use case, I never need to override them. (These classes are simply meant to transmit structured data to other processes, and have no behavior. The source code is generated externally. The protoc compiler provides no mechanism for subclassing, and I don't need it.) 

Furthermore, we already can't override static methods, and it's usually not a problem. Static methods remain very useful. In short, the question of whether static methods should be made overrideable is also a separate question, and is beyond the scope of this discussion. For this use case, I don't need that feature at all.


Submitted On 07-JAN-2010
ggb667
schapel, sorry for the late reply - as I said you could define them as non-static and create an instance and then call the static method of the class.  But that's silly and requires unnecessary jumping though hoops.  



PLEASE NOTE: JDK6 is formerly known as Project Mustang