Saturday, March 17, 2012

All about interfaces in java

public interface Dummy {

protected int x;
}



Above code will give the following error.
Illegal modifier for the interface field Dummy.x; only public, static & final are permitted

If you forget to initialize the variable you will get the following compile time error
The blank final field x may not have been initialized

What if you create a class A which extends B and then create class B to extend A ?
Compiler will say Cycle detected.

You cannot use java reserved words for java package names. For example following is not a valid package com.interface
as interface is a reserved word.


Following code gives an error
package com.intf;

interface Dummy1 {

int x = 10;;
}

interface BigDummy {

int x = 20;

}

class Dummy implements Dummy1, BigDummy {
public static void main(String args) {
System.out.println(x);
}
}



The field x is ambiguous.

Use the below code instead
 
System.out.println(Dummy1.x);
System.out.println(BigDummy.x);




The following code is correct
package com.intf;

interface Dummy1 {

int x = 10;;
void helloWorld();
}

interface BigDummy {

int x = 20;
void helloWorld();
}

class Dummy implements Dummy1, BigDummy {
public static void main(String args[]) {
System.out.println(Dummy1.x);
System.out.println(BigDummy.x);
}

@Override
public void helloWorld() {


}
}




However the following code is not correct. It gives the compiler error.

The return type is incompatible with BigDummy.helloWorld()


This is because the interfaces should have the same function signature.
package com.intf;

interface Dummy1 {

int x = 10;;
void helloWorld();
}

interface BigDummy {

int x = 20;
int helloWorld();
}

class Dummy implements Dummy1, BigDummy {
public static void main(String args[]) {
System.out.println(Dummy1.x);
System.out.println(BigDummy.x);
}

@Override
public void helloWorld() {


}
}

No comments: