Reputation: 16646
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??
Upvotes: 1
Views: 106
Reputation: 21300
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.
Upvotes: 2
Reputation: 16209
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.
Upvotes: 0
Reputation: 11
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.
Upvotes: 0
Reputation: 24630
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)
Upvotes: 2
Reputation: 15433
This is not possible in interfaces. Either you can declare implementable methods or final static constants. But defining constants is not a good practice.
Upvotes: 0
Reputation: 1556
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.
Upvotes: 3
Reputation: 240900
No
Interface is plain contract.
You can only have public
method declaration and public
, static
, final
fields
Nothing else
Upvotes: 2