Initialize a Java Collection in Class that was declared in Interface - java

Declared a Vector in the Interface and set it to null, want to initialize it later in the class that implemented the Interface, java is giving error with the following code, how can i initialize it any other way?
import java.util.Vector;
interface machine {
Vector<Integer> temp = null;
public int compute();
}
class App implements machine {
App(Vector<Integer> x) {
//error here, can't assign value to temp as it is declared in interface, any other way of initializing??
temp = x;
}
#Override
public int compute() {
int sum = 0;
for (int x : temp) {
sum += x;
}
return sum;
}
}
public class Finals {
public static void main(String[] args) {
Vector<Integer> x = new Vector<>();
for (int i = 0; i < 10; i++) {
x.add(i);
}
App a = new App(x);
System.out.println(a.compute());
}
}

Java, the language, is designed with the following ideas in mind:
Fields are never really considered as part of a type's "public API". Yes, a public field can be written and can be modified from the outside, but almost no java code out there does this, and many language features simply do not support it. For example, method references exists (someExpr::someMethodName is legal java), but the there is no such thing as a field reference.
Interfaces exist solely to convey API - to convey what a type is supposed to be able to do, it is not a thing that was intended for conveying how it is to do it. In other words, interface (hence the name) yes, implementation no.
Add these 2 concepts together and you see why what you want (put a field in an interface) is not supported. A field is not part of an interface (rule #1), therefore it must be implementation, and interfaces can not carry implementation details (rule #2), hence: You cannot put a field in an interface.
As a consequence, the java lang spec dictates that any field declaration in an interface is inherently public static final - it's a constant. You can't make it not-public-static-final - putting private on it as modifier is a compiler error. There is no modifier that means 'unstatic'.
You have 2 options:
You intended that field solely as implementation: You decided that all classes that implement this interface will need this field, so, might as well declare it in the interface and save the typing, right? Well, what you're doing there is grouping common aspects of the implementation together. Java supports this, but only in abstract classes. This happens all the time in java: There is java.util.List (an interface), and java.util.AbstractList (an abstract class that implements that interface, that provides a bunch of common behaviour), and java.util.ArrayList (the most commonly used implementation. It extends AbstractList).
You actually need the 'interface' part of that field: You want to write some code, either in the interface file itself (via default methods), or in code that receives an object whose type is your machine interface, and want to directly access the field. When in rome, act like romans. When programming java, act like other java programmers. Which means: Don't treat fields as interface - as API. If the very essence of 'a machine' (that is to say: An object that is an instance of a class, and that class implements machine) is that it can provide a list of integers representing the temp concept, then make that part of the interface: Write Vector<Integer> getTemp; in the interface, and let each implementing class provide an implementation. If you expect that all implementing classes likely just want:
private Vector<Integer> temp;
public Vector<Integer> getTemp() {
return temp;
}
Then you can put that in an abstract class which implements the interface, and have all your impls implement the abstract class.
If this is all flying over your head, I can make it simpler:
All field decls in interfaces are necessarily public static final, whether you write it or not. You can't declare fields that aren't, the language simply won't let you.
There are good reasons for that - see the above explanation.
NB:
You appear to be using some extremely outdated (at least 25 years at this point!!) guidebook. This code wouldn't pass any review as a consequence. Vector is obsolete and should not be used, and has been obsolete for 20 years: You want ArrayList, presumably. Java conventions dictate that TypesGoLikeThis, methodNamesLikeThis, variableNamesAlsoLikeThis, and CONSTANTS_LIKE_THIS. Thus, it'd be public interface Machine, not public interface machine. The compiler lets you do whatever you want, but your code is needlessly weird and inconvenient when you integrate it with any other java code if you fail to follow the conventions.

As per my understanding you can't do it, because interface variables are static final hence you have to initialize in interface itself.

Related

How should I manage constants in a Java project [duplicate]

I'm looking at some open source Java projects to get into Java and notice a lot of them have some sort of 'constants' interface.
For instance, processing.org has an interface called PConstants.java, and most other core classes implement this interface. The interface is riddled with static members. Is there a reason for this approach, or is this considered bad practice? Why not use enums where it makes sense, or a static class?
I find it strange to use an interface to allow for some sort of pseudo 'global variables'.
public interface PConstants {
// LOTS OF static fields...
static public final int SHINE = 31;
// emissive (by default kept black)
static public final int ER = 32;
static public final int EG = 33;
static public final int EB = 34;
// has this vertex been lit yet
static public final int BEEN_LIT = 35;
static public final int VERTEX_FIELD_COUNT = 36;
// renderers known to processing.core
static final String P2D = "processing.core.PGraphics2D";
static final String P3D = "processing.core.PGraphics3D";
static final String JAVA2D = "processing.core.PGraphicsJava2D";
static final String OPENGL = "processing.opengl.PGraphicsOpenGL";
static final String PDF = "processing.pdf.PGraphicsPDF";
static final String DXF = "processing.dxf.RawDXF";
// platform IDs for PApplet.platform
static final int OTHER = 0;
static final int WINDOWS = 1;
static final int MACOSX = 2;
static final int LINUX = 3;
static final String[] platformNames = {
"other", "windows", "macosx", "linux"
};
// and on and on
}
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.
But don't just take my word for it, Josh Bloch also says it's bad:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:
import static com.kittens.kittenpolisher.KittenConstants.*;
This avoids the ugliness of making your classes implement interfaces that have no functionality.
As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place.
But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.)
Eg:
/** Set of constants needed for Kitten Polisher. */
public final class KittenConstants
{
private KittenConstants() {}
public static final String KITTEN_SOUND = "meow";
public static final double KITTEN_CUTENESS_FACTOR = 1;
}
I do not pretend the right to be right, but lets see this small example:
public interface CarConstants {
static final String ENGINE = "mechanical";
static final String WHEEL = "round";
// ...
}
public interface ToyotaCar extends CarConstants //, ICar, ... {
void produce();
}
public interface FordCar extends CarConstants //, ICar, ... {
void produce();
}
// and this is implementation #1
public class CamryCar implements ToyotaCar {
public void produce() {
System.out.println("the engine is " + ENGINE );
System.out.println("the wheel is " + WHEEL);
}
}
// and this is implementation #2
public class MustangCar implements FordCar {
public void produce() {
System.out.println("the engine is " + ENGINE );
System.out.println("the wheel is " + WHEEL);
}
}
ToyotaCar doesnt know anything about FordCar, and FordCar doesnt know about ToyotaCar. principle CarConstants should be changed, but...
Constants should not be changed, because the wheel is round and egine is mechanical, but...
In the future Toyota's research engineers invented electronic engine and flat wheels! Lets see our new interface
public interface InnovativeCarConstants {
static final String ENGINE = "electronic";
static final String WHEEL = "flat";
// ...
}
and now we can change our abstraction:
public interface ToyotaCar extends CarConstants
to
public interface ToyotaCar extends InnovativeCarConstants
And now if we ever need to change the core value if the ENGINE or WHEEL we can change the ToyotaCar Interface on abstraction level, dont touching implementations
Its NOT SAFE, I know,
but I still want to know that do you think about this
There is a lot of hate for this pattern in Java. However, an interface of static constants does sometimes have value. You need to basically fulfill the following conditions:
The concepts are part of the public interface of several
classes.
Their values might change in future releases.
Its critical that all implementations use the same values.
For example, suppose that you are writing an extension to a hypothetical query language. In this extension you are going to expand the language syntax with some new operations, which are supported by an index. E.g. You are going to have a R-Tree supporting geospatial queries.
So you write a public interface with the static constant:
public interface SyntaxExtensions {
// query type
String NEAR_TO_QUERY = "nearTo";
// params for query
String POINT = "coordinate";
String DISTANCE_KM = "distanceInKm";
}
Now later, a new developer thinks he needs to build a better index, so he comes and builds an R* implementation. By implementing this interface in his new tree he guarantees that the different indexes will have identical syntax in the query language. Moreover, if you later decided that "nearTo" was a confusing name, you could change it to "withinDistanceInKm", and know that the new syntax would be respected by all your index implementations.
PS: The inspiration for this example is drawn from the Neo4j spatial code.
Given the advantage of hindsight, we can see that Java is broken in many ways. One major failing of Java is the restriction of interfaces to abstract methods and static final fields. Newer, more sophisticated OO languages like Scala subsume interfaces by traits which can (and typically do) include concrete methods, which may have arity zero (constants!). For an exposition on traits as units of composable behavior, see http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf. For a short description of how traits in Scala compare with interfaces in Java, see http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-5. In the context of teaching OO design, simplistic rules like asserting that interfaces should never include static fields are silly. Many traits naturally include constants and these constants are appropriately part of the public "interface" supported by the trait. In writing Java code, there is no clean, elegant way to represent traits, but using static final fields within interfaces is often part of a good workaround.
According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM
By default, all the methods in interface is abstract even tough you didn't mention it explicitly.
Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.
I do not have enough reputation to give a comment to Pleerock, therefor do I have to create an answer. I am sorry for that, but he put some good effort in it and I would like to answer him.
Pleerock, you created the perfect example to show why those constants should be independent from interfaces and independent from inheritance. For the client of the application is it not important that there is a technical difference between those implementation of cars. They are the same for the client, just cars. So, the client wants to look at them from that perspective, which is an interface like I_Somecar. Throughout the application will the client use only one perspective and not different ones for each different car brand.
If a client wants to compare cars prior to buying he can have a method like this:
public List<Decision> compareCars(List<I_Somecar> pCars);
An interface is a contract about behaviour and shows different objects from one perspective. The way you design it, will every car brand have its own line of inheritance. Although it is in reality quite correct, because cars can be that different that it can be like comparing completely different type of objects, in the end there is choice between different cars. And that is the perspective of the interface all brands have to share. The choice of constants should not make this impossible. Please, consider the answer of Zarkonnen.
This came from a time before Java 1.5 exists and bring enums to us. Prior to that, there was no good way to define a set of constants or constrained values.
This is still used, most of the time either for backward compatibility or due to the amount of refactoring needed to get rid off, in a lot of project.

How to create variable accessible by multiple classes and multiple methods in Java

I would like to create a global variable in my Java program, or at least one that can be accessed by multiple methods of multiple classes. I'm fluent in C, VB6, Jovial, and many other languages, but I don't get Java. I chose it ONLY for WindowBuilder!
Here is some Java-like pseudocode for what I want, minimal to show what I am trying to do. I am aware that it doesn't compile as-is; the point I am focusing on is the NumberOfMembers variable -- how it should be declared and accessed:
public class Prelim {
public String FileName;
public int NumberOfMembers; //instantiate? I've tried all I know
//to do so! Instantiate where, all methods that use?
private void myMethod_a() {
FileName = "C:\myfilename";
ReadRoster();
//modify roster
WriteRoster();
System.out.println(NumberOfMembers);
}
}
public class ReadWriteRoster /* maybe extends Prelim?? */ {
public void ReadRoster(){
//read roster file using FileName
NumberOfMembers = 100;
}
public void WriteRoster(){
//write roster file using FileName
for (int num = 0; num < NumberOfMembers; num++){
}
//do the write`enter code here`
}
}
}
You can use "static" key Word example
static int i = 3;
With this you can access to the variable i in all class of The package and you can import this in all other package.
Java does not offer global variables in the same sense that C and some other languages do. Every variable is associated with a specific class, and often with a particular instance of that class. These two alternatives are distinguished by use of the static keyword, which indicates that the variable (or method or nested class) is associated only with its host class, not with any particular object of that class.
Probably the simplest way to achieve what you asked starts with declaring NumberOfMembers statically, like so:
public class Prelim {
// ...
public static int NumberOfMembers;
// ...
}
Then, everywhere you want to reference it in any other class, you need to qualify its name with the class to tell Java which variable of that name you mean:
// ...
Prelim.NumberOfMembers = 100;
// ...
Although it is not strictly necessary, as a matter of style I recommend using the qualified form even inside the host class.
With that said, what little I see of your code underscores your admission that you don't get Java. Classes should represent things, and to reinforce that to yourself and others, their names should be nouns or noun phrases.
You seem instead to be organizing your classes around steps in your processing algorithm. This leads to a pretty arbitrary arrangement of your code, and directly to some of the questions in code comments about instantiating class Prelim. You are trying to write procedural code, but dressing it up in object-oriented form. You can write procedural code in Java, but it is likely that your task would accommodate a bona fide object-oriented approach as well.
At first glance, an object-oriented version of your code might involve turning it inside out: it looks like it at least wants a class Roster with an instance variable numberOfMembers and methods read() and write(). Those methods could refer to the instance variable naturally, because they would be referring to a member variable of the same object. That would also better accommodate having multiple rosters in the program at the same time, each with its own number of members.
More complex example is using enum types. It is a good practice using enum as singleton.

Best way to create a runtime class-specific register system?

I am currently trying to create a system in which I want to be able to assign unique family ID's to classes at runtime. Essentially I want to be able to distinguish between classes based on a integer-value after having them registered at runtime.
The use-case for this is that this system will be used as the bureaucrazy for a component system. All classes are descendant (not necessarily direct) from a class Component; and are registered at runtime.
I want to be able to do this for several reasons:
Eaze and safety of extension: People will not have to modify a gigantic list in the base component system to add Components.
Efficiency: Lookup internally is done using this integer value so can be O(1) instead of a search lookup. As these components will makeup the bulk of the system, I prefer not to make it an instance variable. I cannot ignore this aspect as testcases have already shown that I cannot afford > O(1) removal and insertion. (A first implementation used map lookup tables)
I am looking for a compile-time checked implementation; not a contract based solution.
A contract based solution in Java would be:
interface Component {
// Should return the value of a static variable
int getFamilyID();
int setFamilyID(int id);
}
class Foo implements Component {
static int familyID = 0;
int getFamilyID(){ return familyID; }
int setFamilyID(int id){ familyID = id; }
}
class System { // Singleton
static int registeredComponents = 0;
void register(Component c){ c.setFamilyID(registeredComponents++); }
}
This obviously doesn't work for two reasons:
I can't specify A.getFamilyID() unless I make the variable public; usecase: c.getFamilyID() == Foo.getFamilyID(); (instead of instanceof)
Redundant code all over the place; each implementation of Component would need to have the copy-pasted implementation.
I thought that I could solve the issue in C++ with a template that specified a static variable, but this becomes unusable when the class is not a direct descendant of Component.
I can also not use enums within Java as they are language-specific and the amount of components would make the code for a single file humongous. (also; they would all have to be specified in a single place again)
Any help in this matter or insight in why I'm trying to "do the wrong thing"(TM) would be quite helpfull :-)
Edit: To clarify, I want some way to ensure at compile-time the code convention of a static integer which can be set in the component class.
What you're basically asking for is that a specific runtime
behavior be checked at compile time. In the general case, that
is simply impossible: you can write all the functions you want,
but the compiler will never be able to ensure that you call a
given function once, and only once, for each type. The best you
can do is use some sort of static variable, make the function
private, and put the call to the registration in the
constructor:
class Component
{
protected:
class Registrator
{
static int nextId;
int id;
public:
Registrator() ; id( nextId ++ ) {}
int id() const { return id; }
};
// ...
};
class Derived ; public Component
{
static Registrator ourId;
// ...
};
(You can do this in Java as well. Just put static Registrator
ourId = new Registrator(); in a static block in each derived
class.)
You still have to require (by contract) that each derived class
contain one, and only one static member of type Registrator.
Off hand, I don't think that you can avoid this.
Note that in general, anytime you have a base class and derived
classes, you'll need to count on contracts. If the base class
has a virtual function clone for example (with the usual
semantics), every derived class must implement it. There's
no way of enforcing this sort of thing at compile time; some of
the programming by contract idioms will allow enforcing at
runtime that the dynamic type of object clone returns is
correct, but there's no way you can enforce, even at runtime,
that the returned object is an actual copy, and not some totally
unrelated instance.
To which all I can say is that I've never found this to be a
problem in practice. Anyone deriving from Component (or any
other base class) must know the contract promessed by
Component. You can (and should) verify some things, but in
the end, you can't verify everything, and in practice, someone
who derives, ignoring the contract, will create code which
doesn't work, and there's not much you can do about it. (Code
review goes a long way here. Particularly code review that also
includes test coverage, insisting that all of the contract
issues are tested)
EDIT:
One final comment: I would argue against using an int for the
identifier. If performance in comparing identifiers is
important, you can still use a char const[]; if you guarantee
that all correctly obtained identifiers point (since the actual
identifier you use will be a char const*) to the same string,
you can just compare pointers. The contract for the derived
class is then:
class Derived : public Component
{
public:
static char const* className() { return "Derived"; }
// overriding virtual function in Component...
char const* type() const { return className(); }
// ...
};
Then, just use the char const* returned by className or
type as your identifier.
That's a bit more for the author of the derived class to type,
but at least in C++, there are always macros to simplify it.
In fact, I would recommend a macro for this sort of thing, even
with the original solution above. If the derived classes all
use a macro, you can change the strategy without changing
anything else.
In C++ you can use the curiously recurring template pattern in order to avoid code repetition.
class Component
{
public:
virtual ~Component() {}
virtual int getFamilyId() const = 0;
};
// each instance is assigned a unique int at construction
class FamilyId
{
static int numberOfExistingIds = 0;
int id;
public:
FamilyId() : id( numberOfExistingIds++ ) {}
int getId() const { return id; }
};
// implementation is done only in this template class
template <typename Derived, typename Base = Component>
class ComponentImpl : public Base
{
static FamilyId familyId; // one instance per class for unique id
public:
virtual int getFamilyId() const
{
assert( typeid(*this) == typeid(Derived) );
return familyId.getId();
}
};
Having set this up, you can easily create new classes in your Component class hierarchy.
// first derived class, automagically implemented by template magic
class MyGeneralComponent
: public ComponentImpl<MyGeneralComponent>
{
/* add new methods here */
};
// class further down in the hierarchy are also possible,
// by using the second template argument. The implementation still works.
class MySpecificComponent
: public ComponentImpl<MySpecificComponent,MyGeneralComponent>
{
/* add new methods here */
};
The assert(...) will automatically check at run-time, if you correctly derived from the template. So you will uncover bugs like
class MySpecificComponent : MyGeneralComponent
{
};
at run-time. This derived class would otherwise use the same interface implementation as the direct base and use the same static variable, which would be a bug.
You might have noticed that you don't need to register any classes by hand. This is done via dynamic initialization of static variables before the main() function starts. So you don't need to do anything about that. In this way you can easily implement your classes in one spot, without changing other files and without lots of code repetition - open/closed principle par excellence.

java : Function objects as strategies

I am reading Effective Java. In a section that talks about using function objects as strategies, the below paragraph is present.
Because the strategy interface serves as a type for all of its concrete strategy
instances, a concrete strategy class needn’t be made public to export a concrete
strategy. Instead, a “host class” can export a public static field (or static factory
method) whose type is the strategy interface, and the concrete strategy class can
be a private nested class of the host
// Exporting a concrete strategy
class Host {
private static class StrLenCmp
implements Comparator<String>, Serializable {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
// Returned comparator is serializable
public static final Comparator<String>
STRING_LENGTH_COMPARATOR = new StrLenCmp();
... // Bulk of class omitted
}
My question is , is there any particular advantage of using the above way? What is the problem with exporting the strategy by making concrete strategy public?
Yes, there is. This way you are returning the interface and not the concrete class, so if you change the concrete implementation of Comparator interface you don't have to modify client classes too (I think this is the most important reason of using interfaces).
For example:
//inside aClass
Comparator c = Host.STRING_LENGTH_COMPARATOR; //Programming against interfaces is different from:
StrLenCmp c = Host.STRING_LENGTH_COMPARATOR; //programming against concrete class
Suppose in the future you will change StrLenCmp with another implementation (let's call it NewStrLenCmp) than if you have programmed against interface Comparator you don't have to modify aClass.
Comparator c = Host.STRING_LENGTH_COMPARATOR; //still work because interface doesn't changed
NewStrLenCmp c = Host.STRING_LENGTH_COMPARATOR; // problem: you need to modify the client class in order to use the new concrete type: bad idea
It's the same problem as making anything public - encapsulation.
The narrowest possible scope for an object makes it much easier to reason about how that object is used, and can ease maintenance massively (you know a private object can only be used in the same source file you're looking at, but you can never truly know how many people are using a public object or in what ways).
Every Java program would work if you declared everything as public, sure. But it's a bit like Pandora's box - once you've opened up access to something, it's hard to take it back.
By not making the concrete strategy public, you prevent other classes/apps being able to use it for their own purposes, which means you don't have to worry about designing it as a fully-fledged, shiny, stable, public class with a well-defined interface. You can just write what works for you, right now, and know that you have the freedom to change it however you want later.
Public stuff is your API. If you ship your code and later need to change your strategy implementation, you have effectively broken your API for everyone you shipped code to.
So until otherwise required, everything should be in the narrowest scope possible.
We also put it into a static nested class because we aren't using this strategy elsewhere.

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