I know, its a stupid question, but someone told me that we can write a code in an interface, i mean not a logic but System.out.println(), in an interface..
Is this true??
-
Your question could be clearer. You cannot have any code in an interface itself, anyway, and inner classes are not the interface ;-)Laurent Pireyn– Laurent Pireyn2011年06月09日 07:54:53 +00:00Commented Jun 9, 2011 at 7:54
-
This might be a good reference point for you to start reading java tutorials. There a lot of texts describing what interfaces are and how you should use them. Mainly you can use them to add functionality to your classes and let the rest of the system know that it has that functionality.Alessandro Vermeulen– Alessandro Vermeulen2011年06月09日 07:56:16 +00:00Commented Jun 9, 2011 at 7:56
8 Answers 8
No, in interface you only declare methods (names, params)
Comments
Interfaces can have just public abstract methods and public static final fields (constants). They CAN'T have: constructors, static blocks, blocks, nonabstract methods, nonpublic methods, non static final fields. If you don't type public static final for fields, or public for methods the compiler adds them for you.
Comments
One thing has been forgotten, an interface can have static classes and interfaces , such as ;
public interface MyInterface {
public static class Holder {};
}
EDIT
JLS states that,
Interfaces may contain member type declarations (§8.5). A member type declaration in an interface is implicitly static and public.
2 Comments
No
Interface is plain contract.
You can only have public method declaration and public, static, final fields
Nothing else
Comments
This is a code example where you can print something out of an interface, but its is bad practice and i know no use case for that, it is only Java puzzeling:
public interface NewClass {
HashMap x = new HashMap() {{
System.err.println("print me");
}};
}
public class Test implements NewClass{
public static void main(String[] args) {
x.clear();
}
}
(The used classes have no further meaning at all)
Comments
This is not possible in interfaces. Either you can declare implementable methods or final static constants. But defining constants is not a good practice.
Comments
Interface is purely Abstract Class Which have only Final Variables,only Abstract methods and it doesn't have any Constructor. So in an interface you can only add only declaration of methods that is only abstract method and Final variables.
Comments
Yes you can:
public interface DoStuff {
public class Worker {
public void work() {
System.out.println("Hi there!");
}
}
}
import DoStuff.Worker;
public class Main {
public static void main(String[] args) {
Worker worker = new Worker();
worker.work();
}
}
If you run Main it will output "Hi there!"
This is a very contrived example, but it is technically possible.