M.J.
M.J.

Reputation: 16646

General question about interfaces

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

Answers (8)

Gursel Koca
Gursel Koca

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

Adriaan Koster
Adriaan Koster

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

DeeP
DeeP

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

PeterMmm
PeterMmm

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

Talha Ahmed Khan
Talha Ahmed Khan

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

Cosmin Cosmin
Cosmin Cosmin

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

Jigar Joshi
Jigar Joshi

Reputation: 240900

No

Interface is plain contract.

You can only have public method declaration and public, static, final fields Nothing else

Upvotes: 2

bigGuy
bigGuy

Reputation: 1744

No, in interface you only declare methods (names, params)

Upvotes: 3

Related Questions