Let's say I have a method getAverageDifficulty in my class Difficulty that goes like this:
public static Float getAverageDifficulty (List<Difficulty> difficultyList) {
...
return average;
}
My method obviously needs to be static, since it makes no sense requiring an instance of Difficulty. Now let's say I'm using an interface IDifficulty so I can change my implementation later. Obviously, I do want my getAverageDifficulty method to be available from IDifficulty, and, as I can't declare a static method abstract, the obvious option is to put getAverageDifficulty directly in my interface. My question is: am I making a mistake by putting that static method in my interface, which contains other Difficulty methods waiting to be implemented? Should I not mix static and "normal" interface abstract methods? Should I create DifficultyHelper class and put my method there?
Ultimately, this is a matter of style. However, if the only purpose of the helper class is to hold this method (and maybe a few similar ones), then you will be saving yourself one class definition by placing them in the interface:
As of Java 8, the restriction that interfaces cannot contain static methods was eliminated, so there is typically little reason to provide a noninstantiable companion class for an interface [Effective Java, 3rd edition].
Static methods in interfaces are similar to the default methods except that we cannot override these methods in the classes that implements these interfaces.so in my opinion its not not necessary to write static methods in interfaces until you want to prevent overriding.
Related
public interface Drive {
int getNumWheels();
default int driveMiles(){
return 10;
}
static int getColorID(){
return 0;
}
}
In the code above, why doesn't the static method in an interface not need a default access modifier? I understand that the default method was added in JDK 8, and provides an optional implementation, however, I am a little unclear about the static method? This seems really similar to a class's static method?
In the code above, why doesn't the static method in an interface not need a default access modifier?
I guess you are asking, why is it static and not static default?
In classes you can just use static and most likely they thought it would be simpler to keep it consistent.
This seems really similar to a class's static method?
Which is why I believe the syntax is the same.
A better question would be
why do we use default as a modifier at all?
There is two reasons I can think of
default is already a keyword so easy to reuse in the language and it is used in a similar way in annotations.
it makes it clear that this method is intended to have an implementation. They could have dropped the need for a keyword at all, but a little redundancy can improve code quality.
why did they decide to include static in an interface for JDK 8?
The benefit is the same as for a class. You can define a method which is associated with an interface but is not tied to a particular class. A good example is factory classes. In the past you would have to have say
Logger LOGGER = LoggerFactory.getLogger(...);
If you wanted Logger to be an interface, it's factory method, which must be static had to use a utility class. Now your API could be
Logger LOGGER = Logger.get(...);
The interface for the factory method is the same as the interface it returns so there is less reason to quality exactly what type get returns.
There is a difference in purpose of default and static methods.
When you extend an interface that contains a default method, you can do the following:
Not mention the default method at all, which lets your extended interface inherit the default method.
Redeclare the default method, which makes it abstract.
Redefine the default method, which overrides it.
Static Methods
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.
If you are redefining static method in another class, you are hiding the definition in first interface.
Refer to oracle documentation page about default and static methods.
I wondered if it would be possible to call from a POJO a singleton bean's method through its interface. Maybe this idea is wrong or the architecture...but this is what I would like to accomplish if it is possible, because this is the architecture of the project.
I notice that when I call getInstance() (the method from the singleton's interface) from the POJO, there is an error occuring, telling me that the method has to be static, but if I make the method static, then I have to write the implementation in the interface and I can't get the singleton instance.
Your current approach with the interface is flawed. By default, all methods in an interface (up until Java 8) are static, and are implemented by instance methods in the implementing class.
This means, this is not an option. After all, you'll need to run the method to create an instance, meaning, you don't have an instance yet, so you have no instance to call it on.
Putting the same static method in an abstract class you extend, is also not a solution: a super class should never be aware of it's subclasses. If it is a static method (which it needs to be), you need to keep it in the class itself: a static method in an abstract class can (through an anonymous implementation of the abstract class) return an instance of the abstract class, but this is not the same as an instance of the subclass, which is what you are looking for.
In order to use this method for the subclass, you will need to inherit it from the super class. But, it will still return an instance of the super class. You'll need to overwrite the method in the subclass by the correct one, so the best solution is to add it straight in your Singleton class.
You are not allowed to have static methods in your interfaces (at least not until Java 8). Something like this is not allowed:
MyInterface var = new MyImplementingClass();
var.staticMethod();
Just remove the interface and do your static method call against the class where the static method resides.
Search a bit for the singleton pattern - the 'standard' way to do this involves classes and not interfaces, so rethink your design.
The idea seems to be wrong. A static method is always at a class level and hence you can never declare a method as static in a Java interface(you can do this in Java 8). However, this seems like the wrong design. If you really want to do something like this -
1)Make the Interface an abstract class.
2)Create a static method called getInstance();
3)Extend the abstract class in your POJO singleton class.
Hope this helps!!
Is there a way to call a method in one class from another class. I could have say 5 classes and more than one may want to perform the same operation. So can I have one file (class??) with these common methods and call into that? If so what is the necessary modifier for these 'common' methods - public, final??
If anyone can point me to a suitable tutorial I would be grateful - in this instance I havent had much useful from Google
Thanks
Ron
This is a simple example for a (utility) class with a method that can be used from any other class:
public class Util {
public static int sizeOf(String input) {
return input.size();
}
}
To make it work "right out of the box": choose public and static as access modifiers for the method. Just like all methods from the well known java.lang.Math class.
I'd go with a general tutorial on OOP and how to use classes, e.g.
http://download.oracle.com/javase/tutorial/java/javaOO/classes.html
Basically you can call any method from another class, as long as it's public. If the method is static, you don't even need to instantiate it. But read some tutorials to get the basic idea of OOP instead of just looking for a solution for your specific problem, it'll help a lot more!
You probably want to create a "Utility" class. You can use the static keyword to make your methods static:
public UtilityClass {
public static int myMethod(String arg) {
}
}
result = UtilityClass.myMethod("sdfs");
In the implementation of the static methods you can't use local fields, unless you also mark them as static.
You can either make these methods public static.
An other way would be to pass instances of these other classes into your class. Maybe as a method parameter, set-method or parameter of the constructor.
I'm just curious, wouldn't it be more convinient to allow interfaces to contain implementations of static methods? Such methods could contain short commonly used(by this interface implementors) logic.
Because an interface describes what. It doesn't describe how.
If you really want to add (hide) some logic inside an interface, you may consider adding an inner class (Note: never do it, this just shows what is possible from a pure technical perspective):
public interface Person {
public String getFirstName();
public String getLastName();
public class Util {
public String getName(Person person) {
return person.getFirstName() + " " + person.getLastName();
}
}
}
If you use this, it "feels" a bit like having static method code in the interface:
String fullName = Person.Util.getName(this);
As I said - it's pure technically and I don't see any reason to actually do it. A static method can be located in any class, no need to add it to an interface.
An interface is a contract. It says what an implementing object will have (at minimum), but that's all. It says "this house will have a door, a window, and a chimney".
An abstract class is more like a prefab house. It's not complete (you have to add your own siding, for example) but it has parts already there (there is a space for the door, but the whole fireplace is already setup.
The problem with giving code in interfaces is multiple inheritance. Java doesn't allow it. You can have a class implement many interfaces, because interfaces only promise there will be a method with a given signature.
If interfaces held code, then you could implement 3 of them, each with a method body for myUsefulFunction(String thing)... and now you don't know which one gets called.
That's why abstract classes can have method bodys (because you can only extend one class), but interfaces can't (because you can implement multiple interfaces).
I agree that a static method doesn't make sense in an interface. But i don't understand why java allows static members in an interface. Seems a bit inconsistent.
It's the abstract class or regular class which should implement something. Interfaces are not supposed to have any implementations, but they contain the interface of communicating. So static methods are not allowed.
An interface is a special abstract class with all abstract methods.
You can feel free to create an abstract class of your own that contains (non-abstract) static methods, but then you can only inherit from one of them.
Better yet, create a separate helper class with your static methods.
why we should not use static and abstract for a single method?
the static keyword is defined so that a method can be called by a class name rather then an object. that means the method has to have some sort of definition. but abstract means you do not have any details about what the method does, it is as it says **Abstract**. When you inherit or extend a class you can then define the method.
Think of an interface.
If you are asking about having a static method inside of an abstract class, that is a different story. An abstract class is essentially as mentioned an interface and contains just a template of say functions that you must later on implement by inheriting / extending the class. Once you extend that class the static method does not come along with it (that is by default unless the access modifier is public / protected).
A static method is not inherited. Therefore, making it abstract is a nonsense.
The abstract keyword means that child classes must override the method - this is (one of the ways) Java supports polymorphism. If you want to make it so that subclasses cannot override the method you mark it final. So it would be impossible to have an "abstract final" method since they are the exact opposite of each other.
the static keyword implies final as well - all static method are also final. Thus it is impossible to have a method that is both static and abstract since you would be able to make a method that is abstract and final.
The reason for static being final is that it is bound to the class instead of the instance. That means that the compiler looks it up at compile time rather than runtime to determine which method to call. The reason what it is like that? Arbitrary decision that the designers of Java made - they could have allowed static method to be overridden but decided not to. I don't have any particular insight as to why the chose one over the other unfortunately.
As others have said, static+abstract is nonsense in Java. But there have been (rare) occasions where I've wished I could do just that.
The result I was looking for was basically to say that... "all concrete classes that extent this abstract class (or implement this interface) must provide a static method with this signature." This capability would allow these classes to provide meta-information about themselves.
Normally I have ended up with an instance method in these cases. If you stipulate that concrete implementations must support the default (no-arg) constructior, you can do...
MyInterface obj = MyClassThatImplementsMyInterface.newInstance();
obj.invokeTheMethodIWishWasBothStaticAndAbstract();