why Java 8 interface static methods cannot override Object class methods [duplicate] - java

I'm confused why the following is not allowed:
public interface MyInterface {
MyInterface getInstance(String name);
}
public class MyImplementation implements MyInterface {
public MyImplementation(String name) {
}
#Override
public static MyInterface getInstance(String name) { // static is not allowed here
return new MyImplementation(name)
}
}
I understand why a method in the interface cannot be static, but why can't the overriding method be?
I want all classes to implement the getInstance(String name) method, but I'm currently limited to only being able to call the method if the object has already been instantiated which kind of defeats the purpose...
*update:* Thanks for the answers, I understand it better now. Basically I shouldn't be trying to make a utility class (or a factory class for that matter) implement an interface (or at least, not in this way)...

Invoking static methods in Java requires you to specify the exact type. It is not possible to invoke static methods polymorphically, eliminating the need for #Override.
Please note that this approach is not universal across all languages: for example, you can override class methods in Objective-C, and Apple's cocoa frameworks make good use of this mechanism to customize their "factory" classes. However, in Java, C++, and C# class methods do not support polymorphic behavior.
Theoretically, Java designers could have let you provide interface method implementations through static methods in case an implementation does not need to access the state from the instance. But the same behavior is simple to achieve with a trivial wrapper:
public class MyImplementation implements MyInterface {
public MyImplementation(String name) {
}
#Override
public MyInterface getInstance() { // static is not allowed here
return getInstanceImpl();
}
public static getInstanceImpl() {
return new MyImplementation(name)
}
}
Java compiler could have done the same thing on your behalf, but seeing a static method implement an instance method is both unusual and confusing, so my guess is that Java designers decided against providing this "piece of magic".

Static methods cannot be subject to polymorphic behavior. That would not make much sense. Image this use case, assuming what you want would be possible:
public void foo(MyInterface i) {
i.getInstance("abc");
}
now I want to call this method with an implementation of MyInterface (class A), but since I cannot pass the class itself, I need to pass an object:
A a = new A();
foo(a);
now inside foo the static override of getInstance is called on the instance of class A. So now I am stuck with creating an object just to call a static method.
My point is that you would still be constrained to create an object in most use cases of polymorphism since in your original interface the method was an instance method.

because implementing an interface makes the implementor the type of the interface. That means instances need to have the methods defined by the type, not the class of the instances.
To put it another way,
public void mymethod
and
public static void mymethod
are NOT the same method declaration. They are completely distinct. If mymethod is defined on an interface, having the second definition simply does not satisfy implementing the interface.

The answer comes down to what it means to implement an interface. When a class implements an interface, that is a promise that every instance of the class will respond to every method in the interface. When you implement the method as static, you make it possible to call the method without an instance of the class - but that doesn't fulfill the inheritance implementation's promise that the method will be callable on every instance of the class.

Related

Using default keyword in interface correctly

I have a co worker who need a method to be available to two classes.
He decided to create a new interface to be implemented by those classes.
The interface has one method
default doThis(String parameter)
It does not have any other interface methods, there is no indication that other methods would be added to this interface.
I feel this is an incorrect usage of the interface and it should be done in a different way. I.e perhaps a class which has the method allowing other classes to consume this by using the object.
Does anyone with experience on this have any opinions to share?
I can update with more clarification based on your comments.
Update:
Here is the code and the question remains:
is this a valid use of the default method or should this common logic have been done in another way like a Utilities class which does the saving to preferences ?
Interface:
public interface LogInCookie {
default void mapCookiesToPreferences(String cookie) {
if (cookie.contains(MiscConstants.HEADER_KEY_REFRESH)) {
String refreshToken = cookie.replace(MiscConstants.HEADER_KEY_REFRESH, StringUtils.EMPTY);
SharedPrefUtils.addPreference(SharedPrefConstants.REFRESH_TOKEN, refreshToken);
}
}
}
public class HDAccountActivity extends AbstractActivity implements LogInCookie {
private void mapCookies(List<String> mValue) {
LogInCookie.super.mapCookiesToPreferences(mValue); //ekh!
}
}
public class BaseSplashPage extends AppCompatActivity implements DialogClickedCallBack, LogInCookie {
//method which uses this
private void mapCookiesToPreferences(List<String> headers) {
int firstItemInHeader = 0;
for (String header : headers) {
String mValue = header.substring(firstItemInHeader,header.indexOf(MiscConstants.SEMICOLON));
LogInCookie.super.mapCookiesToPreferences(mValue); //ekh!
}
}
}
A default method in an interface, which doesn’t define other methods, can’t do much useful things with the instance of the implementing class. It can only use methods inherited from java.lang.Object, which are unlikely to carry semantics associated with the interface.
If the code doesn’t use instance methods on this at all, in other words, is entirely independent from the this instance, you should make it static, change the containing class to a non-instantiable class type, i.e.
final class SomeUtilClass {
static void doThis(String parameter) {
// ...
}
private SomeUtilClass() {} //no instances
}
and use import static packageof.SomeUtilClass.doThis; in the classes using this method.
That way, all these classes can invoke the method like doThis(…) without a qualifying type name, without needing a misleading type hierarchy.
When the method actually uses the this instance, which, as said, can only be in terms of methods inherited from java.lang.Object, the type inheritance might be justified. Since this is rather unlikely, you might still consider the type hierarchy to be misleading and rewrite the code to
final class SomeUtilClass {
static void doThis(Object firstParameter, String parameter) {
// ...
}
private SomeUtilClass() {} //no instances
}
using firstParameter instead of this, which can be invoke like doThis(this, …).
Ideally you would put that method doThis() in an abstract class that both classes extend. However if you need to achieve multiple inheritance then using an interface here is fine.
A class with a static method doThis() that you can call staticly would also work.
It all depends on how you have your project organized imo.
In java 8 , default keyword in interface was introduced for those cases where if any set of apis had long inheritance hierarchy and we wanted to introduce a method that should be available in all of the lower lying classes.
So for ex. in Java 8 stream() method was introduced in the Collection interface as a default method and it ended up being available in all of the underlying classes.
As far as your case in considered , if I go by your words then if yours is a new development then you should be using interface -> abstract class -> actual implementing class.
Only if yours was an older development setup and you already had classes implementing from an interface , that could have been an ideal scenario for using default method in your interface.
A default method in an interface
*)can have a default implementation
*)which can overridden by the implementing class
yes its a correct usage since JAVA8.
we can have default method in an interface as well as a abstract method

Using Singleton Design with Inheritance in a multithreaded Application

I am having an application where code is somewhat written like this
public Interface SuperCLass{
//....to do some methods
}
public class BaseClass1 implements SuperCLass{
//....to do some methods
}
public class BaseClass2 implements SuperCLass{
//....to do some methods
}
Now in my application only one object can be instantiated for SuperClass reference, i.e a synchronized singleton.
Now, I can include
public static synchronized SuperCLass getInstance(){
//initialise
}
in any of the base classes, but I cannot include this declaration in SuperClass interface due to which I cannot get back instance of base class using reference of super class.
e.g.
I want to do this(its a very vague example)
BaseClass1 bc1 = BaseClass1.getInstance();
SuperClass sc = bc1.getInstance();
Now somewhere later in the code
bc1=sc.getInstance();
How can this be achieved?
Note: Several threads would be accessing these objects hence synchronisation is mandatory
Instead of using singletons why dont you use dependency injection eg: google guice.
Guice will create the instance of the super class for you and then you can access it via the injector.getInstance() method.
First of all you will have to synchronize the access to the instance. There are plenty of examples on how to do that (such as thread safe publishing of a read only or threadsafe class).
Because a singleton means a static method. You have to decide which implementation is used somewhere. Normally this is through a setInstance method.
One way to make a Superclass method return a Subclass type is through Generics.
You will not be able to make the methods static as you cannot override static methods so this technique will not help you but it would go something like:
public interface SuperClass<T extends SuperClass<T>> {
public T getInstance();
}
public class BaseClass1 implements SuperClass<BaseClass1> {
#Override
public BaseClass1 getInstance() {
// Do my create.
}
}
However, for your specific need of requiring thread-safe Singletons extending a base class you could use an enum as a factory for them and use a Multiton to ensure there is only ever one of them.

Why Interface methods cannot be "static" & "final"?

In Java Interface, we can have only final variables possible. We can also create static variables in Interface. But, at the same time we are not able to create static/final methods as Interface are only meant for Static Methods.
What is exactly the reason for not allowing static/final methods in Interface ?
A final method can't be overridden. That defies the purpose of having an interface if you cannot actually implement the method.
For the static part, see this question.
You got it wrong.
All variables are implicitly public static and final in interfaces.
Prior to Java 8, you can't create static methods in interfaces. All methods are instance methods.
Since the only goal of an interface is to have classes implementing them, and since methods in interfaces can't have any implementation, making them final would make no sense: they would have no implementation, and could not be overridden.
Interfaces are defined for instances, not statics.
"final" means "can't be overridden". That makes no sense for an interface whatsoever.
final means that it cannot be overriden.
static means that it can only be called using the class name. Since an interface will have multiple implementations, how will you know which implementation to choose since the interface cannot implement the method itself?
Because they are there in an interface to be implemented by some class. What would be the point of a method that can not have an implementation anywhere? (which is what final would suggest)
I have one more point to prove why interface methods can not be static :
interface MyInterface {
static void myStaticMethod();
}
Now let's have two classes are implementing "MyInterface"
// first class
class MyClass1 implements MyInterface {
static void myStaticMethod(){
// some implementation
}
}
// second class
class MyClass2 implements MyInterface {
static void myStaticMethod(){
// some implementation
}
}
Now I am instantiating like below:
1- MyInterface myObj1 = new MyClass1();
2- myObj1.myStaticMethod();
3- MyInterface myObj2 = new MyClass2();
4- myObj2.myStaticMethod();
// here at line 2 & 4 , it's wrong calling as myStaticMethod should be called using class name(because myStaticMethod is defined as static) like below:
MyInterface.myStaticMethod();--> But in this case,how to call different implementations of myStaticMethod() by MyClass1 & MyClass2 classes.
So it's proved that static can not be possible in interface method declaration.
For final ,it's quite clear that it will opposite to override functionality.
An interface is a pure abstract class. Hence, all methods in an interface are abtract, and must be implemented in the child classes. So, by extension, none of them can be declared as final.
Why Interface methods cannot be “static” & “final”?
All methods in an interface are explicitly abstract and hence you cannot define them as static or final because static or final methods cannot be abstract.
In the context of Java 8 and default methods, this question has a new meaning. static methods are now allowed, and why final methods still aren't possible is explained in this question.
1: we can't declare a final method ,because it contradicts it's rule as final method can't be override,but always need to define all the interface methods in it implemented classes.
2: we can't declare a static method ,because it contradicts it's rule as static method always needs the method body but we cant define any method inside a interface.
Well static methods work on classes and not instances so kind of strange/pointless. Having said that I've for one reason or another wanted this in some situations, though can't remember a case now so must have been long ago.
You can "work around" this though (rather alternative api design) as interfaces allow you to declare classes, so something like this:
interface MyInterface {
static class Helpers {
static void myStaticMethod(); //can be abstract etc as usual
}
}
You can subclass that class etc as normal of course, as well make it abstract, abstract methods etc etc.
We can not declare method of interface as static because method of interface instance method and we can not declare final because it is necessory to override method of interface in implemented class. for description check this link enter link description here
By default all the methods present inside an interface are public and abstract. If you declair a method as final inside an interface 1st of all you will get a compiler error and not even then it doesn't make any sense to have a final method because you will never be in a position to override it in child class.
In case of static even if Java allow in what so ever version it's not a good programming practice to use static inside an interface because for static methods u must have to provide the implementation which you must not provide inside an interface. Moreover, even if you provide the implementation inside an interface still u have to override it and then have to call it by the class name.
Interface cant have static method because if you know the static property that method declared static can be called without creating any object of class and sttaic methods are part of class not instance of class, so the answer is that how can you call abstract method till java 7, In java 8 you can declare method as static and call it by interface name dot method name.
Now answer fo final is that , final method is not overriden so how you will override it when class will inherit it
why can't we make Interface methods final?
because if you make a method final then you can not override it and the sole purpose of Interface is to have methods that will be overridden by all those class that implements that Interface.
why can't we make Interface methods static?
In Java 8 it's possible, you can make methods static but that method should have a method body
interface Test{
static void hello(){
System.out.println(“hello world”);
}
}
and you can access this method from a class implementing this Interface by
Test.hello();

Can i call a method which is inside an interface without implementing the interface?

Can i call a method inside an interface without implementing the interface in my class?
package;
import Contact;
public interface IPerson{
public void savePerson(Contact contact);
}
Now some class here...
public class HulkHogan {
//Calling the method savePerson here
//I dont want to implement the Interface in all.
}
Statically, you can declare it to be called. You don't necessarily have to implement the interface inside the calling class. For example:
public class HulkHogan {
private IPerson person;
public HulkHogan(IPerson person){
this.person = person;
}
public void doSomething(Contant contact){
//call your method here
person.savePerson(contact);
}
}
But in order to execute it, you will need to implement it somewhere, because interface just describes how something behaves but does not provide the actual behaviour (i.e. does not implement it).
You can in this way :
Person p = new IPerson{
public void savePerson(Contact contact) {
// some code
}
}
Now call savePerson on p. You are implementing IPerson without creating a separate class.
You can't because the method doesn't contain a definition (method body). The purpose of a interface is to implement it somewhere so that you have an actual implementation of this method.
No you cant...bcoz all methods of the class interface are abstract..and you cant use them without implementing the class ...
No You can't call it, You will have to provide its implementation atleast
Further to call method you will need an object. you can't instantiate interface without its implementation provided
The interface is just a definition of methods without implementation. If you are not implementing the methods what will they do when you call them?
On the other hand, an interface is not necessarily implemented by the calling class. So in your case HulkHogan can call another object's savePerson() method, without implementing it itself. But some class has to implement it somewhere for it to do something.
Unless you implement the interface or have a member object of a class that implements the interface, you can not use the savePerson method, since by definition it has no implementation yet.
You'd have to call it on an object which is an instance of the interface, so either HulkHogan would have to implement IPerson or an instance of something which implements IPerson would have to be supplied to (or instantiated within, though that is not preferred) HulkHogan.
More to the point (based also on your previous questions), what do you expect to accomplish by calling a method which has no implementation?
The goal of an interface is to mandate a specific and well-known contract for a known type of object. For example, by tradition all Stacks have push(), pop(), and peek(). So by writing an interface, you're expressly writing a contract that anyone who writes a stack should follow.
To put in another way, it is a template that dictates that any class that calls itself a Stack must implement methods called push(), pop(), and peek() as my example here discusses.
public interface StackInterface {
public void push(int x);
public int pop();
public void peek();
}
public class myStack implements StackInterface{
}
It's an object-oriented technique. At this point you will not get a compile because you haven't at least implemented methods for the interface methods. You will need to write methods matching the signatures of the Interface before you can fully use the interface.
when you say you are implementing an interface for a class, you actually mean you are abiding a contract (or a discipline) which is defined in the interface, that is you will give the definition for the method in interface, so just feel that interface is a container which contains a rule,
You said you want to call the method in the interface : that is not a method in itself that is just a rule defined so what is the point is calling a method which has no body (actually is its not a method in itself)
...enjoy
You can create a Proxy which does nothing to mock out calls to the interface. However this effectively creates an implementation dynamically. You cannot avoid providing an implementation of some kind.
public class HulkHogan {
private IPerson person;
public void setContactM(IPerson person) {
this.person= person;
}
public void doSomething(Contact contact) {
person.savePerson(contact);
}
}
Hope the savePerson method has some definition somewhere in other class which implements it. Through this way you can call the method inside your interface.
You can't call the method while it does not have an implemented body. The implementing class will give it the body that you need.
In Java 8, you can implement the method body inside the interface itself, and using the static access modifier for it. In this case you just need to import the interface in your current class (in case it is in a different package) and then you can call the method directly.

Why can't I define a static method in a Java interface?

EDIT: As of Java 8, static methods are now allowed in interfaces.
Here's the example:
public interface IXMLizable<T>
{
static T newInstanceFromXML(Element e);
Element toXMLElement();
}
Of course this won't work. But why not?
One of the possible issues would be, what happens when you call:
IXMLizable.newInstanceFromXML(e);
In this case, I think it should just call an empty method (i.e. {}). All subclasses would be forced to implement the static method, so they'd all be fine when calling the static method. So why isn't this possible?
EDIT: I guess I'm looking for answer that's deeper than "because that's the way Java is".
Is there a particular technological reason why static methods can't be overwritten? That is, why did the designers of Java decide to make instance methods overrideable but not static methods?
EDIT: The problem with my design is I'm trying to use interfaces to enforce a coding convention.
That is, the goal of the interface is twofold:
I want the IXMLizable interface to allow me to convert classes that implement it to XML elements (using polymorphism, works fine).
If someone wants to make a new instance of a class that implements the IXMLizable interface, they will always know that there will be a newInstanceFromXML(Element e) static constructor.
Is there any other way to ensure this, other than just putting a comment in the interface?
Java 8 permits static interface methods
With Java 8, interfaces can have static methods. They can also have concrete instance methods, but not instance fields.
There are really two questions here:
Why, in the bad old days, couldn't interfaces contain static methods?
Why can't static methods be overridden?
Static methods in interfaces
There was no strong technical reason why interfaces couldn't have had static methods in previous versions. This is summed up nicely by the poster of a duplicate question. Static interface methods were initially considered as a small language change, and then there was an official proposal to add them in Java 7, but it was later dropped due to unforeseen complications.
Finally, Java 8 introduced static interface methods, as well as override-able instance methods with a default implementation. They still can't have instance fields though. These features are part of the lambda expression support, and you can read more about them in Part H of JSR 335.
Overriding static methods
The answer to the second question is a little more complicated.
Static methods are resolvable at compile time. Dynamic dispatch makes sense for instance methods, where the compiler can't determine the concrete type of the object, and, thus, can't resolve the method to invoke. But invoking a static method requires a class, and since that class is known statically—at compile time—dynamic dispatch is unnecessary.
A little background on how instance methods work is necessary to understand what's going on here. I'm sure the actual implementation is quite different, but let me explain my notion of method dispatch, which models observed behavior accurately.
Pretend that each class has a hash table that maps method signatures (name and parameter types) to an actual chunk of code to implement the method. When the virtual machine attempts to invoke a method on an instance, it queries the object for its class and looks up the requested signature in the class's table. If a method body is found, it is invoked. Otherwise, the parent class of the class is obtained, and the lookup is repeated there. This proceeds until the method is found, or there are no more parent classes—which results in a NoSuchMethodError.
If a superclass and a subclass both have an entry in their tables for the same method signature, the sub class's version is encountered first, and the superclass's version is never used—this is an "override".
Now, suppose we skip the object instance and just start with a subclass. The resolution could proceed as above, giving you a sort of "overridable" static method. The resolution can all happen at compile-time, however, since the compiler is starting from a known class, rather than waiting until runtime to query an object of an unspecified type for its class. There is no point in "overriding" a static method since one can always specify the class that contains the desired version.
Constructor "interfaces"
Here's a little more material to address the recent edit to the question.
It sounds like you want to effectively mandate a constructor-like method for each implementation of IXMLizable. Forget about trying to enforce this with an interface for a minute, and pretend that you have some classes that meet this requirement. How would you use it?
class Foo implements IXMLizable<Foo> {
public static Foo newInstanceFromXML(Element e) { ... }
}
Foo obj = Foo.newInstanceFromXML(e);
Since you have to explicitly name the concrete type Foo when "constructing" the new object, the compiler can verify that it does indeed have the necessary factory method. And if it doesn't, so what? If I can implement an IXMLizable that lacks the "constructor", and I create an instance and pass it to your code, it is an IXMLizable with all the necessary interface.
Construction is part of the implementation, not the interface. Any code that works successfully with the interface doesn't care about the constructor. Any code that cares about the constructor needs to know the concrete type anyway, and the interface can be ignored.
This was already asked and answered, here
To duplicate my answer:
There is never a point to declaring a static method in an interface. They cannot be executed by the normal call MyInterface.staticMethod(). If you call them by specifying the implementing class MyImplementor.staticMethod() then you must know the actual class, so it is irrelevant whether the interface contains it or not.
More importantly, static methods are never overridden, and if you try to do:
MyInterface var = new MyImplementingClass();
var.staticMethod();
the rules for static say that the method defined in the declared type of var must be executed. Since this is an interface, this is impossible.
The reason you can't execute "result=MyInterface.staticMethod()" is that it would have to execute the version of the method defined in MyInterface. But there can't be a version defined in MyInterface, because it's an interface. It doesn't have code by definition.
While you can say that this amounts to "because Java does it that way", in reality the decision is a logical consequence of other design decisions, also made for very good reason.
With the advent of Java 8 it is possible now to write default and static methods in interface.
docs.oracle/staticMethod
For example:
public interface Arithmetic {
public int add(int a, int b);
public static int multiply(int a, int b) {
return a * b;
}
}
public class ArithmaticImplementation implements Arithmetic {
#Override
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = Arithmetic.multiply(2, 3);
System.out.println(result);
}
}
Result : 6
TIP : Calling an static interface method doesn't require to be implemented by any class. Surely, this happens because the same rules for static methods in superclasses applies for static methods on interfaces.
Normally this is done using a Factory pattern
public interface IXMLizableFactory<T extends IXMLizable> {
public T newInstanceFromXML(Element e);
}
public interface IXMLizable {
public Element toXMLElement();
}
Because static methods cannot be overridden in subclasses, and hence they cannot be abstract. And all methods in an interface are, de facto, abstract.
Why can't I define a static method in a Java interface?
Actually you can in Java 8.
As per Java doc:
A static method is a method that is associated with the class in which
it is defined rather than with any object. Every instance of the class
shares its static methods
In Java 8 an interface can have default methods and static methods. This makes it easier for us to organize helper methods in our libraries. We can keep static methods specific to an interface in the same interface rather than in a separate class.
Example of default method:
list.sort(ordering);
instead of
Collections.sort(list, ordering);
Example of static method (from doc itself):
public interface TimeClient {
// ...
static public ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
System.err.println("Invalid time zone: " + zoneString +
"; using default time zone instead.");
return ZoneId.systemDefault();
}
}
default public ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
}
Interfaces are concerned with polymorphism which is inherently tied to object instances, not classes. Therefore static doesn't make sense in the context of an interface.
First, all language decisions are decisions made by the language creators. There is nothing in the world of software engineering or language defining or compiler / interpreter writing which says that a static method cannot be part of an interface. I've created a couple of languages and written compilers for them -- it's all just sitting down and defining meaningful semantics. I'd argue that the semantics of a static method in an interface are remarkably clear -- even if the compiler has to defer resolution of the method to run-time.
Secondly, that we use static methods at all means there is a valid reason for having an interface pattern which includes static methods -- I can't speak for any of you, but I use static methods on a regular basis.
The most likely correct answer is that there was no perceived need, at the time the language was defined, for static methods in interfaces. Java has grown a lot over the years and this is an item that has apparently gained some interest. That it was looked at for Java 7 indicates that its risen to a level of interest that might result in a language change. I, for one, will be happy when I no longer have to instantiate an object just so I can call my non-static getter method to access a static variable in a subclass instance ...
"Is there a particular reason that static methods cannot be overridden".
Let me re-word that question for your by filling in the definitions.
"Is there a particular reason that methods resolved at compile time cannot be resolved at runtime."
Or, to put in more completely, If I want to call a method without an instance, but knowing the class, how can I have it resolved based upon the instance that I don't have.
Static methods aren't virtual like instance methods so I suppose the Java designers decided they didn't want them in interfaces.
But you can put classes containing static methods inside interfaces. You could try that!
public interface Test {
static class Inner {
public static Object get() {
return 0;
}
}
}
Commenting EDIT: As of Java 8, static methods are now allowed in interfaces.
It is right, static methods since Java 8 are allowed in interfaces, but your example still won't work. You cannot just define a static method: you have to implement it or you will obtain a compilation error.
Several answers have discussed the problems with the concept of overridable static methods. However sometimes you come across a pattern where it seems like that's just what you want to use.
For example, I work with an object-relational layer that has value objects, but also has commands for manipulating the value objects. For various reasons, each value object class has to define some static methods that let the framework find the command instance. For example, to create a Person you'd do:
cmd = createCmd(Person.getCreateCmdId());
Person p = cmd.execute();
and to load a Person by ID you'd do
cmd = createCmd(Person.getGetCmdId());
cmd.set(ID, id);
Person p = cmd.execute();
This is fairly convenient, however it has its problems; notably the existence of the static methods can not be enforced in the interface. An overridable static method in the interface would be exactly what we'd need, if only it could work somehow.
EJBs solve this problem by having a Home interface; each object knows how to find its Home and the Home contains the "static" methods. This way the "static" methods can be overridden as needed, and you don't clutter up the normal (it's called "Remote") interface with methods that don't apply to an instance of your bean. Just make the normal interface specify a "getHome()" method. Return an instance of the Home object (which could be a singleton, I suppose) and the caller can perform operations that affect all Person objects.
Why can't I define a static method in a Java interface?
All methods in an interface are explicitly abstract and hence you cannot define them as static because static methods cannot be abstract.
Well, without generics, static interfaces are useless because all static method calls are resolved at compile time. So, there's no real use for them.
With generics, they have use -- with or without a default implementation. Obviously there would need to be overriding and so on. However, my guess is that such usage wasn't very OO (as the other answers point out obtusely) and hence wasn't considered worth the effort they'd require to implement usefully.
An interface can never be dereferenced statically, e.g. ISomething.member. An interface is always dereferenced via a variable that refers to an instance of a subclass of the interface. Thus, an interface reference can never know which subclass it refers to without an instance of its subclass.
Thus the closest approximation to a static method in an interface would be a non-static method that ignores "this", i.e. does not access any non-static members of the instance. At the low-level abstraction, every non-static method (after lookup in any vtable) is really just a function with class scope that takes "this" as an implicit formal parameter. See Scala's singleton object and interoperability with Java as evidence of that concept.
And thus every static method is a function with class scope that does not take a "this" parameter. Thus normally a static method can be called statically, but as previously stated, an interface has no implementation (is abstract).
Thus to get closest approximation to a static method in an interface, is to use a non-static method, then don't access any of the non-static instance members. There would be no possible performance benefit any other way, because there is no way to statically link (at compile-time) a ISomething.member(). The only benefit I see of a static method in an interface is that it would not input (i.e. ignore) an implicit "this" and thus disallow access to any of the non-static instance members. This would declare implicitly that the function that doesn't access "this", is immutate and not even readonly with respect to its containing class. But a declaration of "static" in an interface ISomething would also confuse people who tried to access it with ISomething.member() which would cause a compiler error. I suppose if the compiler error was sufficiently explanatory, it would be better than trying to educate people about using a non-static method to accomplish what they want (apparently mostly factory methods), as we are doing here (and has been repeated for 3 Q&A times on this site), so it is obviously an issue that is not intuitive for many people. I had to think about it for a while to get the correct understanding.
The way to get a mutable static field in an interface is use non-static getter and setter methods in an interface, to access that static field that in the subclass. Sidenote, apparently immutable statics can be declared in a Java interface with static final.
Interfaces just provide a list of things a class will provide, not an actual implementation of those things, which is what your static item is.
If you want statics, use an abstract class and inherit it, otherwise, remove the static.
Hope that helps!
You can't define static methods in an interface because static methods belongs to a class not to an instance of class, and interfaces are not Classes. Read more here.
However, If you want you can do this:
public class A {
public static void methodX() {
}
}
public class B extends A {
public static void methodX() {
}
}
In this case what you have is two classes with 2 distinct static methods called methodX().
Suppose you could do it; consider this example:
interface Iface {
public static void thisIsTheMethod();
}
class A implements Iface {
public static void thisIsTheMethod(){
system.out.print("I'm class A");
}
}
class B extends Class A {
public static void thisIsTheMethod(){
System.out.print("I'm class B");
}
}
SomeClass {
void doStuff(Iface face) {
IFace.thisIsTheMethod();
// now what would/could/should happen here.
}
}
Something that could be implemented is static interface (instead of static method in an interface). All classes implementing a given static interface should implement the corresponding static methods. You could get static interface SI from any Class clazz using
SI si = clazz.getStatic(SI.class); // null if clazz doesn't implement SI
// alternatively if the class is known at compile time
SI si = Someclass.static.SI; // either compiler errror or not null
then you can call si.method(params).
This would be useful (for factory design pattern for example) because you can get (or check the implementation of) SI static methods implementation from a compile time unknown class !
A dynamic dispatch is necessary and you can override the static methods (if not final) of a class by extending it (when called through the static interface).
Obviously, these methods can only access static variables of their class.
While I realize that Java 8 resolves this issue, I thought I'd chime in with a scenario I am currently working on (locked into using Java 7) where being able to specify static methods in an interface would be helpful.
I have several enum definitions where I've defined "id" and "displayName" fields along with helper methods evaluating the values for various reasons. Implementing an interface allows me to ensure that the getter methods are in place but not the static helper methods. Being an enum, there really isn't a clean way to offload the helper methods into an inherited abstract class or something of the like so the methods have to be defined in the enum itself. Also because it is an enum, you wouldn't ever be able to actually pass it as an instanced object and treat it as the interface type, but being able to require the existence of the static helper methods through an interface is what I like about it being supported in Java 8.
Here's code illustrating my point.
Interface definition:
public interface IGenericEnum <T extends Enum<T>> {
String getId();
String getDisplayName();
//If I was using Java 8 static helper methods would go here
}
Example of one enum definition:
public enum ExecutionModeType implements IGenericEnum<ExecutionModeType> {
STANDARD ("Standard", "Standard Mode"),
DEBUG ("Debug", "Debug Mode");
String id;
String displayName;
//Getter methods
public String getId() {
return id;
}
public String getDisplayName() {
return displayName;
}
//Constructor
private ExecutionModeType(String id, String displayName) {
this.id = id;
this.displayName = displayName;
}
//Helper methods - not enforced by Interface
public static boolean isValidId(String id) {
return GenericEnumUtility.isValidId(ExecutionModeType.class, id);
}
public static String printIdOptions(String delimiter){
return GenericEnumUtility.printIdOptions(ExecutionModeType.class, delimiter);
}
public static String[] getIdArray(){
return GenericEnumUtility.getIdArray(ExecutionModeType.class);
}
public static ExecutionModeType getById(String id) throws NoSuchObjectException {
return GenericEnumUtility.getById(ExecutionModeType.class, id);
}
}
Generic enum utility definition:
public class GenericEnumUtility {
public static <T extends Enum<T> & IGenericEnum<T>> boolean isValidId(Class<T> enumType, String id) {
for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
if(enumOption.getId().equals(id)) {
return true;
}
}
return false;
}
public static <T extends Enum<T> & IGenericEnum<T>> String printIdOptions(Class<T> enumType, String delimiter){
String ret = "";
delimiter = delimiter == null ? " " : delimiter;
int i = 0;
for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
if(i == 0) {
ret = enumOption.getId();
} else {
ret += delimiter + enumOption.getId();
}
i++;
}
return ret;
}
public static <T extends Enum<T> & IGenericEnum<T>> String[] getIdArray(Class<T> enumType){
List<String> idValues = new ArrayList<String>();
for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
idValues.add(enumOption.getId());
}
return idValues.toArray(new String[idValues.size()]);
}
#SuppressWarnings("unchecked")
public static <T extends Enum<T> & IGenericEnum<T>> T getById(Class<T> enumType, String id) throws NoSuchObjectException {
id = id == null ? "" : id;
for(IGenericEnum<T> enumOption : enumType.getEnumConstants()) {
if(id.equals(enumOption.getId())) {
return (T)enumOption;
}
}
throw new NoSuchObjectException(String.format("ERROR: \"%s\" is not a valid ID. Valid IDs are: %s.", id, printIdOptions(enumType, " , ")));
}
}
Let's suppose static methods were allowed in interfaces:
* They would force all implementing classes to declare that method.
* Interfaces would usually be used through objects, so the only effective methods on those would be the non-static ones.
* Any class which knows a particular interface could invoke its static methods. Hence a implementing class' static method would be called underneath, but the invoker class does not know which. How to know it? It has no instantiation to guess that!
Interfaces were thought to be used when working with objects. This way, an object is instantiated from a particular class, so this last matter is solved. The invoking class need not know which particular class is because the instantiation may be done by a third class. So the invoking class knows only the interface.
If we want this to be extended to static methods, we should have the possibility to especify an implementing class before, then pass a reference to the invoking class. This could use the class through the static methods in the interface. But what is the differente between this reference and an object? We just need an object representing what it was the class. Now, the object represents the old class, and could implement a new interface including the old static methods - those are now non-static.
Metaclasses serve for this purpose. You may try the class Class of Java. But the problem is that Java is not flexible enough for this. You can not declare a method in the class object of an interface.
This is a meta issue - when you need to do ass
..blah blah
anyway you have an easy workaround - making the method non-static with the same logic. But then you would have to first create an object to call the method.
To solve this :
error: missing method body, or declare abstract
static void main(String[] args);
interface I
{
int x=20;
void getValue();
static void main(String[] args){};//Put curly braces
}
class InterDemo implements I
{
public void getValue()
{
System.out.println(x);
}
public static void main(String[] args)
{
InterDemo i=new InterDemo();
i.getValue();
}
}
output :
20
Now we can use static method in interface
I think java does not have static interface methods because you do not need them. You may think you do, but...
How would you use them? If you want to call them like
MyImplClass.myMethod()
then you do not need to declare it in the interface. If you want to call them like
myInstance.myMethod()
then it should not be static.
If you are actually going to use first way, but just want to enforce each implementation to have such static method, then it is really a coding convention, not a contract between instance that implements an interface and calling code.
Interfaces allow you to define contract between instance of class that implement the interface and calling code. And java helps you to be sure that this contract is not violated, so you can rely on it and don't worry what class implements this contract, just "someone who signed a contract" is enough. In case of static interfaces your code
MyImplClass.myMethod()
does not rely on the fact that each interface implementation has this method, so you do not need java to help you to be sure with it.
What is the need of static method in interface, static methods are used basically when you don't have to create an instance of object whole idea of interface is to bring in OOP concepts with introduction of static method you're diverting from concept.

Categories

Resources