No static methods for Interfaces ?
Hi,
I was going though some documentation about the interfaces and it says that, an interface methods must not be static.
Can someone please explain or direct me in the direction which tell me why the internet methods cannot be static.
Thanx.
Mel
Defining a static method in a interface would be useless, since static methods can't be executed with dynamic binding. You'd have to know the name of the implementing class of the interface at compile time to call it, which would negate the need for an interface.
For more details google it, that question has been asked thousands of times.
Similar Messages
-
Static methods in interface (Yes, once again!)
I know there has been many questions about why static methods in interfaces are not allowed. I know it is forbidden by the JLS. But does anyone know the exact reason for this? Is it just a design issue or are there technical difficulties with allowing it?
I can't think of any reason that it should be impossible to allow static methods in interfaces. I don't even think it would be very difficult to do. More importantly, it could probably be done without breaking existing code and existing JVMs (not too sure about the last one).
So once again: Was the choice of not allowing static methods in interfaces a design choice or a technical choice?A better example of what you are suggesting is surely ...
interface i {
static void one();
class a implements i {
static void one() {
// do something
class b implements i {
static void one() {
// do something else
}What would be the point of ever doing this?
You cant call i.one() as the method doesn't exist without an instance of an implementing class.
To actually ever be able to use that method you would effectively be casting an INSTANCE of a or b -> i. If you have an instance of an a or b then there is absolutely no reason for that method to be static.
If you wanted to implement some sort of class (ie static) behaviour then class a could call its own internal static method from within the 'one' method.
To get right to the point ... there isn't one. If it gets added to the language (and I can't see it in my wildest dreams) then Sun have lost their marbles, surely?
Unless someone can give a good example of when it might be correct and useful to do so? I can't even see how it would be a convenience as it is completely unusable, no? -
Singleton or static methods for DAO?
Which is the preferred way of creating a DAO which has no state...Singleton or static methods for DAO? and why? What are the issues implement one over the other?
A [url http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html]DAO is an object that abstracts different data source access mechanisms by providing a common interface, decoupling the client code from the data layer implementation, and allowing differrent data sources to be used without changing the client code.
This is not possible with static methods- you would have to change the client code to use a different data source.
There is a similar pattern, the facade, where an object/utility class provides the interface to a set of functionality. In the case of a facade with static methods, the facade class needs to be rewritten to use a different implementation. This is possible, but means only one implementation may exist in each version of the software. A static method facade is a tighter coupled solution to a similar problem; tight coupling occasionally makes a measurable improvement in performance, but always reduces flexibility and requires destructive editing to change its implementation.
Pete -
Why not to use static methods in interfaces?
why?
Because static methods are always attached to a particular class -- not an object. So object polymorphism (which is what interfaces are good for) won't help. Now, what you can do is say that subclasses must implement a method that looks an awful lot like a static method, in that it doesn't depend on object state.
This bugged me, and it still bugs me a little bit in that I have to instantiate an object of a type in order to call these pseudo-static methods. When the pseudo-static methods tell the user how to initialize the object, you get a bit of a chicken-and-egg problem. -
Java cognoscenti,
Anyone know why I can't declare a method as static in an interface, but I can in an abstract class. Surely, semantically it's the same - defering the implementation of a static method, not an abstract class and an interface. By the way, I'm using JDK 1.2.2 if that makes a differenceNo, it's not the same. You are not "defering the
implementation of a static method" because static
methods are never polymorphic.
Static methods cannot be abstract for this reason, and
only abstract methods are allowed in interfaces.I didnt't know that. I thought that - because you can override static methods and you can call them onto an actual instance the method binding would be done at run-time, not at compile-time. So I was trying to prove you wrong, but you are correct !
A short summary of what I've learnt so far:
- interfaces cannot contain static methods
- abstract classes cannot contain abstract static methods
- static methods can be overriden, but they are not polymorphic; this means that the compiler decides which method to call at compile-time.
/* output
SuperClass.someMethod()
SubClass.someMethod()
SuperClass.someMethod()
SuperClass.someMethod()
SubClass.someMethod()
SubClass.someMethod()
SuperClass.someMethod()
public class Test {
public final static void main(String[] args) {
// output: SuperClass.someMethod()
new SuperClass().someMethod();
// output: SubClass.someMethod()
new SubClass().someMethod();
// output: 2x SuperClass.someMethod()
SuperClass someClass1 = new SubClass();
someClass1.someMethod();
showSuper(someClass1);
// output: 2x SubClass.someMethod()
SubClass someClass2 = new SubClass();
someClass2.someMethod();
showSub(someClass2);
showSuper(someClass2); // SuperClass.someMethod()
public final static void showSuper(SuperClass c) {
c.someMethod();
public final static void showSub(SubClass c) {
c.someMethod();
class SuperClass {
public static void someMethod() {
System.out.println("SuperClass.someMethod()");
class SubClass extends SuperClass {
public static void someMethod() {
System.out.println("SubClass.someMethod()"); -
Static methods inside interfaces
Why they are not allowed? Such methods would be very helpful in some cases. I speak, of course, about method declaration, not method definition.
Ok , now I understand the problem. Thanks.
And it's also impossible to override a staticmethod.
Actually, it is very possible.Nope. That's hiding (or is it shadowing?), not overriding.
The thing is, it only makes sense to have methods in an interface that can be overridden--by the JLS' definition of overriding--that is, where the particular method implementation that gets invoked is determined at runtime.
Since static method invocatinos are compile-time bound, there's no reason for them to be in an interface--or indeed abstract at all, whether in an interface or abstract class. -
I'm writting a wrapper for exception handling.One of the classes uses log4j to log exceptions.I want to write a interface to generalize loggin.Idealy I should have an interface with certain static methods for loging (i.e logError,logDebugMessage,consoleError,consoleMessage,etc) , but Interface dosent allow that and neither do abstract classes can havstatic method declarations.The implementations of these methods will achieve the hiding of the complexity of using a logging package,log levels etc from the user.
Let me know how best I can work something out for this.
Thanks in advanceDefine them once (as final) in an abstract class. Then any subclass can call logError etc.
Kind regards,
Levi -
Static methods, what for?
What are static methods for? is there something that is not possible through methods associated with instances (non-static methods) ?
There are many examples of static mehods in the Java API. For example the Math or the System class. All methods in this classes are static. So you dont have to instantiate the system class. In fact it is even not possible to instantiate the System class. System is final and all Constructors are private.
Another use for static methods is the access to private static variables. -
Why is it that the interfaces cannot have static methods?
why is it that the interfaces cannot have static methods?
Interfaces contain polymorphic methods. Static methods are not polymorphic, and therefore would not make any sense to be in interfaces.
-
I have a static method in my class .
Now i want to change my class to Distributed class
So what to do with that static method ...
I can't take in interface , so how i can call that method
Sunil VirmaniThe pre condition of all the remote methods is that they should have been declared in the interface implementing RemoteInterface. Now its been discussed in detail in this forum already why we cannot have static methods declared in the interface therefore by nature not being polymorphic u cannot use static methods for the aforesaid purpose.
-
From Classic abap FMs to ObjectOriented instance/static methods: reference
Hi All,
we are migrating one of our project developed using classic abap to abap objects.
mostly we are replacing the Function modules with either instance methods or static methods.
for e.g.
if there are FMs like GUI_UPLOAD, SO_NEW_DOCUMENT_SEND_API1 are used, after exploring in sdn for abap objects, we realized
we can use cl_gui_frontend_services=>gui_upload( ) instead of the GUI_UPLOAD.
send_request = cl_bcs=>create_persistent( ). send_request->send( ). can be used instead of SO_NEW_DOCUMENT_SEND_API1
like that there are several FMs present, is there any easy way where we can find this reference of object oriented methods corresponding to the plain old Function modules of classic abap.
i was thinking, after seeing the blogs of people like Thomas Jung, Horst Keller, they encouraged a lot on abap objects over procedural abap. are there any such guidlines, references present to migrate (rather upgrade) to abap objects from existing procedural abap
thanks,
Madhu_1980I don't think it makes sense to do 1:1 mapping and replacement in your code.
It does make sense to refactor using Object oriented techniques and patterns but it is usually a non-trivial task. -
How to create a method for reading a file
i tried to make it as static method for reading a file and
then to return string
is this code correct?
public static String fileMaterial(String fileName)
fileReader = new BufferedReader(new FileReader(fileName));
info = fileReader.readLine();
while(school != null) {
return info;
info = fileReader.readLine();I created a class you might want to look at. I come from a world of C and love fgets() and other FILE stream functions. I created a class that uses the Java I/O buts to the calling application behaves like fgets and such. The block of code where I do the calling in the calling program even looks like C. In my class I capture almost all errors and set error buffers to the errors. The calling program looks at the return to see if it succedded or errored.
BuffIO new = BuffIO.fopen("fiilename", "r");
String s;
if((s = new.fgets()) == null)
System.err.println("error reading file: " + new.ferror());
That would be waht the calling program does -
Why is the static method in the superclass more specific?
Why is the static method in the superclass more specific than the static method in the subclass? After all, int is a subtype of long, but Base is not a subtype of Sub.
class Base {
static void m(int i){ System.out.println("Base"); }
class Sub extends Base {
static void m(long l){ System.out.println("Sub"); }
class Test {
public static void main(String[] args) {
int i = 10;
Sub sub = new Sub();
sub.m(i);
}The first example compiles without error.
Output: Base
class Base {
void m(int i){ System.out.println("Base"); }
class Sub extends Base {
void m(long l){ System.out.println("Sub"); }
class Test {
public static void main(String[] args) {
int i = 10;
Sub sub = new Sub();
sub.m(i);
}In the second example, both instance methods are applicable and accessible (JLS 15.12.2.1), but neither is more specific (JLS 12.2.2), so we get a compiler error as expected.
: reference to m is ambiguous,
both method m(int) in Base and method m(long) in Sub match
sub.m(i);
^
1 error
Why don�t we get a compiler error for the static methods?Thank you for your ideas.
====
OUNOS:
I don't get Sylvia's response. This is about static methods, what are instances are needed for??Yes, the question is about static methods. I included the example with non-static methods for a comparison. According to JLS 15.12.2, both examples should cause a compiler error.
And why you create a Sub object to call the method, and dont just call "Sub.m(..)"Yes, it would make more sense to call Sub.m(i). Let�s change it. Now, I ask the same question. Why is there no compiler error?
====
DANPERKINS:
The error in your logic stems from calling static methods on instances, as ounos pointed out. Solution: don't. You won't see any more ambiguities.A static member of a class may also be accessed via a reference to an object of that class. It is not an error. (The value of the reference can even be null.)
Originally I was looking only at the case with non-static methods. Therefore, I used sub.m(i). Once I understood that case, I added the static modifiers. When posting my question, I wish I had also changed sub.m to Sub.m. Either way, according to JLS 15.12.2, a compiler error should occur due to ambiguous method invocation.
====
SILVIAE:
The question was not about finding an alternative approach that doesn't throw up an ambiguity. The question related to why, in the particular situations described, the ambiguity arises in only one of them.
Yes.
Proposing an alternative approach doesn't address the question.
Yes.
====
If anyone is really interested, here is some background to the question. Some people studying for a Sun Java certificate were investigating some subtleties of method invocations:
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=019182
I remember seeing the non-static case discussed in this forum once before in a more practical context. jschell probably knows the link. -
Why is it necessary to create an instance via the static method?
Hi,
For some classes (such as java.util.regex.Pattern), we should call the class method (static method) in order to create an instance (object).
For example, in order to conduct the pattern matching, we should use the java.util.regex.Pattern class as follows:
Pattern p = Pattern.compile ("X[0-9]+X") ;
// An instance of the Pattern class is created.
Matcher m = p.matcher ("abcX1XYX23Xz") ;
while ( m.find() ){
System.out.println ( m.start() ) ;
}where the compile static method in the Pattern class creates an instance and returns the pointer (reference) of it. We should NOT call
the constructor of the Pattern class as follows:
Pattern p = new Pattern ("X[0-9]+X") ; // ERRORThe question is the following:
(1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?
(2) Why do the java.util.regex.Pattern class have such a specification?
Thanks in advance.(1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?1. As the other author mentioned, caching is one reason.
2. With such caching, you don't need to take trouble in passing the reference of a cached object(s) to many places in your code. From anywhere in your code base, you can simply invoke the method, the object will come. In essence, the static method provides a global point of access to one or more pre-created (or cached) objects. Hence, the static method simplifies access to the object.
3. Sometimes, the actual class instantiated is not the same as the one with the static method. This allows abstraction of underlying variations. For example, when you say Pattern.compile ("X[0-9]+X") , the returned object type can be different in Windows and Linux (Most probably Pattern class doesn't work like that, but I am showing you a use case. May be Runtime.getRuntime() does actually work like that.). You find this abstraction of variations in many places. Take for example, FacesContext.getExternalContext() method (this is from JSF API). ExternalContext documentation says this:
"This class allows the Faces API to be unaware of the nature of its containing application environment. In particular, this class allows JavaServer Faces based appications to run in either a Servlet or a Portlet environment."
Edited by: Kamal Wickramanayake on Oct 24, 2012 8:04 AM -
Help to solve the static method....pls.
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class Main {
public Main() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
String[] subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class create_table {
public create_table() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
substring(subStr); //problem at here
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// problem at here
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
static void substring(String[] subStr)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
String text;
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
*on top is the original code, bottom is after modified
i would like to create a static method for the static void substring(String[] subStr). But when i use the substring() on the main program, the compiler give me error. Is that my substring () created wrongly?? pls help...package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class Main {
public Main() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
String[] subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr = text.substring(index); // extract to the end
else // otherwise
subStr = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
package readtext;
import java.io.*; // For input & output classes
import java.util.Date; // For the Date class
public class create_table {
public create_table() {
public static void main(String[] args)
throws IOException{
BufferedReader in = new BufferedReader(
new FileReader("C:/Documents and Settings/seng/Desktop/testfile/txt.txt"));
*use ' ' as a separator, and rearrange back the datastream column
String text;
while ((text = in.readLine()) != null)
String[] subStr;
String[] substring;
int i;
substring(subStr); //PROBLEM: substring in readtext can not apply
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
// Directory name
File aFile = new File(dirName, "data.txt");
aFile.createNewFile(); // Now create a new file if necessary
if(!aFile.isFile()) // Verify we have a file
System.out.println("Creating " + aFile.getPath() + " failed.");
return;
BufferedWriter out = new BufferedWriter(new FileWriter(aFile.getPath(), true));
* Display output at data.txt file
// provide initial (X,Y,Z) coordinates for mobiles
out.write("$node_(" + subStr[0] + ") set X_ " + subStr[0] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Y_ " + subStr[1] +
System.getProperty("line.separator") +
"$node_(" + subStr[0] + ") set Z_ " + subStr[2] +
System.getProperty("line.separator"));
out.flush();
out.close();
static void substring(String[] subStr)
int count = 0; // Number of substrings
char separator = ' '; // Substring separator
String text;
// Determine the number of substrings
int index = 0;
do
++count; // Increment count of substrings
++index; // Move past last position
index = text.indexOf(separator, index);
while (index != -1);
// Extract the substring into an array
subStr = new String[count]; // Allocate for substrings
index = 0; // Substring start index
int endIndex = 0; // Substring end index
for(int i = 0; i < count; i++)
endIndex = text.indexOf(separator,index); // Find next separator
if(endIndex == -1) // If it is not found
subStr[i] = text.substring(index); // extract to the end
else // otherwise
subStr[i] = text.substring(index, endIndex); // to end index
index = endIndex + 1; // Set start for next cycle
the problem is here
String text;
while ((text = in.readLine()) != null)
String[] subStr;
String[] substring;
int i;
substring(subStr); //PROBLEM: substring in readtext can not apply
String dirName = "C:/Documents and Settings/seng/Desktop/testfile";
the system say that my substring(subStr[i]) (java.lang.String[])in read.text can not applied to (java.lang.String)...how can i solve for tis problem? is that i have to use for loop to create an array for subStr???
Maybe you are looking for
-
Problems with my USB 2.0.4 card working with my ipod 3RD GEN
So I have a 3rd Generation ipod 15gigs and I wanted to install a USB 2 card in my Mac desktop (G4 Dual) since my fire ports have been giving me issues when I try to tranfer things to my ipod. I then went out and purchased a (Dynex USB 2.0.4 Port PCI
-
HP Color Laserjet 1515n won't print
Haven't been able to find an answer anywhere. Even disconnected from the network and stand-alone, the HP Color LaserJet 1515n (product number CC377A bought at Costco not too long ago) won't print. Can't print configuration page, no demo page. Noth
-
DC containing UI component of task is not available
Genereating version ID's for sources... Compiling workflow... [BpemTask] WARNING: [System.err] [Invoked from com.sap.bc.krn.perf.PerfTimes.internal_TRC(PerfTimes.java:103)] [BpemTask] WARNING: [System.err] PerfTimes : loadNativeLayer: loading jp
-
Please help whenever I try to log into FaceTime it's says unable to connect please check you network connection than try again I've tried everything and even waited up to an month for something to change but nothing has!! Please Help!!!
-
Gateway server is going to grey stage:
Hi All, In my company one of the management server goes down,the gateway server reporting to that management server becomes grey,unfortunately there was no fail over server. i tried the below step its working for a while but with in minutes the gatew