Java

자바 프로그래밍 (Java) - 32 : 인터페이스 예제

n.han 2016. 7. 14. 10:27

다음은 Lendable 인터페이스를 구현한 SeparteVolume, AppCDInfo 클래스를 작성한 예제이다.

 

AppCDInfo는 동시에 CDInfo라는 클래스를 상속 받는 것을 볼 수 있다.

 

main 함수에서는 향상된 for문과 다형성을 사용하여 Lendable 타입으로 객체들을 관리하는 것을 볼 수 있다.

 

public interface Bookable {

        void book();

}

public interface Lendable {

        final static int MAX1 = 100;     

        public void checkOut() throws Exception;

        void checkIn() throws RuntimeException;

}

class CDInfo {

    String title;

}

class AppCDInfo extends CDInfo implements Lendable  {

    public void checkOut() throws Exception {

        if(title == null)

                throw new Exception();

        System.out.println(title + "AppCDInfo Check Out...");

    }

    public void checkIn() {

        System.out.println("AppCDInfo Check In...");

    }  

}

class SeparateVolume  implements Lendable, Bookable {

    public void checkOut() {

        System.out.println("Volume Check Out...");

    }

    public void checkIn() {

        System.out.println("Volume Check In...");

    }

    // Book 메서드

public void book() {

        System.out.println("Volume Booking...");

}

}

public class MainClass {

        public static void main(String args[]) {

        Lendable[] arr = { new SeparateVolume(), new AppCDInfo()};

        for( Lendable var : arr ){

            try {

                var.checkOut();

            } catch (Exception e){

                System.out.println(e);

            }

        }

}