22 Haziran 2009 Pazartesi

Java Interface ile Taklalar

Bir interface'in içinde başka bir interface, hatta public class tanımlamak mümkün imiş. İlk dosyamız OuterInterface.java:

public interface OuterInterface {

public abstract void doOuterInterfaceThing();

public interface InnerInterface{
public abstract void doInnerInterfaceThing();
}

public class ClassInTheInterface{
private static String slogan;
ClassInTheInterface(){
slogan = "Worst decision is better than no decision.";
}
public void speakOut(){
System.out.println(slogan);
}
}
}

Şimdi de hem dıştaki, hem de içteki interface'leri implement eden bir class yazalım. Bu class, haliyle her iki interface'in abstract method'larını implement edecek. Ek olarak da OuterInterface'in içinde tanımlanan public class'ı kullansın. İkinci dosya TestClass.java:

public class TestClass implements OuterInterface, OuterInterface.InnerInterface{

public void doInnerInterfaceThing() {
System.out.println("I am doing the inner interface thing.");
}

public void doOuterInterfaceThing() {
System.out.println("I am doing the outer interface thing.");
}

public static void main(String[] args){
TestClass obj1 = new TestClass();
obj1.doInnerInterfaceThing();
obj1.doOuterInterfaceThing();

OuterInterface.ClassInTheInterface obj2 = new OuterInterface.ClassInTheInterface();
obj2.speakOut();
}
}

Output:
I am doing the inner interface thing.
I am doing the outer interface thing.
Worst decision is better than no decision.

Böylece başımız göğe ermiş bulunuyor. Hayırlı uğurlu olsun.

Hiç yorum yok:

Yorum Gönder