public interface Car {
    void start();
    void stop();
    void aircon();
    void radio();
    void navi();
    
}​

 

// Car 인터페이스의 일부 기능을 구현하기 위한 추상 클래스
// 모든 Car구현객체가 동일하게 구현하는 내용을 미리 구현해서
// 구현 클래스의 구현 부담을 줄이는 역할을 수행한다.

public abstract class AbstractCar implements Car {
    public void start() {
        System.out.println("자동차를 출발시킨다.");
    }

    public void stop() {
        System.out.println("자동차를 정지시킨다.");
    }
}​

 

public class Tico extends AbstractCar {
    public void aircon() {
        System.out.println("티코는 찬바람만 나옴");
    }

    public void radio() {
        System.out.println("티코는 라디오가 나옴");
    }

    public void navi() {
        System.out.println("티코는 길찾기 기능을 지원하지 않음");
    }
}
​

 

public interface Highpassable {
    void highpass();
}​

 

public interface HeadupDisplayable {
    void headupDisplay();
}​

 

public interface Camera {
    void record();
    
}​

 

public interface AutoDrivable {
    void  autoDrive();
}​

 

// 인터페이스는 다른 인터페이스를 하나 이상 상속받을 수 있다.
public interface Safeable extends Camera, AutoDrivable {
    void airbag();
}
​

 

public class Genesis extends AbstractCar implements Highpassable, HeadupDisplayable, AutoDrivable {
    public void aircon() {
        System.out.println("제네시스는 설정된 온도로 냉방을 유지함");
    }

    public void radio() {
        System.out.println("제네시스는 자동으로 라디오 주파수 채널을 검색함");

    }

    public void navi() {
        System.out.println("제네시스는 목적지까지 경로를 안내함");
    }

    public void highpass() {
        System.out.println("제네시스는 하이패스를 지원함");
    }

    public void headupDisplay() {
        System.out.println("제네시스는 교통정보를 앞유리창에 표시합니다.");
    }

   public void autoDrive() {
        System.out.println("제네시스는 자율 정보를 표시합니다.");
    }

    public void airbag() {
        System.out.println("제네시스는 에어백을 지원합니다.");
    }
}
​

 

public class CarApp {
    public static void main(String[] args) {

        Tico obj1 =  new Tico();
        obj1.start();
        obj1.stop();
        obj1.navi();
        obj1.aircon();
        
        Car obj2 = new Tico();
        obj2.start();
        obj2.stop();
        obj2.navi();
        obj2.aircon();

        Genesis obj3 = new Genesis();
        obj3.start();
        obj3.stop();
        obj3.navi();
        obj3.aircon();
        obj3.autoDrive();
        obj3.highpass();
        obj3.airbag();
        obj3.radio();
        obj3.headupDisplay();

        Car obj4 = new Genesis();
        obj4.start();
        obj4.stop();
        obj4.navi();
        obj4.aircon();

        AutoDrivable car5 = new Genesis();
        car5.autoDrive();
    }
}
​

 

public interface DataReader {
    void read();
}​

 

public class DatabaseDataReader implements DataReader {
    public void read() {
        System.out.println("데이터베이스에서 필요한 데이터를 읽는다.");
    }
}​

 

public class NetworkDataReader implements DataReader {
    public void read() {
        System.out.println("네트워크 통신을 통해서 필요한 데이터를 읽는다.");
    }
}
​

 

public class HRMgr {
    // DataReader 인터페이스를 구현한 객체가 연결될 잭(그릇)을 선언
    private DataReader reader;

    public void setReader(DataReader reader) {
        this.reader=reader;
        }

        public void load() {
            reader.read();
        }
}​

 

public class HRMgrApp {
    public static void main(String[] args) {
        HRMgr mgr = new HRMgr();
        //DataReader인터페이스를 구현한 NetworkDataReader객체 생성
        NetworkDataReader reader1 = new NetworkDataReader();
        //HRMgr의 reader 잭에 위에서 생성한 NetworkDataReader객체 연결
        mgr.setReader(reader1);

        mgr.load();

        DatabaseDataReader reader2 = new DatabaseDataReader();
        mgr.setReader(reader2);
        mgr.load();
    }
}​

 

public class Category {
    private int no;
    private String name;

    // 기본 생성자
    public Category() {}

    // 필드를 초기화하는 생성자
    public Category(int no, String name) {
        this.no = no;
        this.name = name;
    }

    // Getter/Setter 메소드
    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}​

 

public class Product {
    private int no;
    private String name;
    private int price;
    private Category cat;

    // 기본 생성자
    public Product() {}

    // Getter/Setter
    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Category getCat() {
        return cat;
    }

    public void setCat(Category cat) {
        this.cat = cat;
    }

    public void printDetail() {
        System.out.println("상품     번호 " + no);
        System.out.println("상품     이름 " + name);
        System.out.println("상품     가격 " + price);
        System.out.println("카테고리 번호 " + cat.getNo());
        System.out.println("카테고리 이름 " + cat.getName());
        System.out.println();
    }
}
​

 

public class MallService {
    private Category[] categories = new Category[10];
    private Product[] products = new Product[100];

    private int catPosition = 0;
    private int proPosition = 0;

    public MallService() {
        categories[catPosition++] = new Category(100, "가구");
        categories[catPosition++] = new Category(200, "가전제품");
        categories[catPosition++] = new Category(300, "주방용품");
        
    }
    
    // 새로운 카테고리 등록 기능
    public void addCategory(Category category) {
    //    for (catPosition; catPosition<categories[].length) {
    //    categories[catPosition] = category;
    //    catPosition++
    //    }
            categories[catPosition] = category;
            catPosition++;
    
    }

    public Category getCategory(int categoryNo) {
        Category category = null;
        
        for (Category cat : categories) {
            if (cat != null && cat.getNo() == categoryNo) {
                category = cat;
            }
        }

        return category;
    }

    public void addProduct(Product product) {
        //for (proPosition; proPosition<products[].length) {
        //products[proPosition] = product;
        //proPosition++
        products[proPosition] = product;
        proPosition++;
        }

    public void printAllCategories() {
        for    (Category c : categories) {
            if (c != null) {
            System.out.print("카테고리 번호 : " + c.getNo());
            System.out.print("카테고리 이름 : " + c.getName());

            }
        }
    }

    public void printAllProducts() {
        for    (Product p : products) {
            if (p != null){
                p.printDetail();
            }
        }
    }
    
    public void printProductsByCategory(int categoryNo) {
        for (Product p : products) {
            if (p != null) {
                Category c = p.getCat();
                if (c.getNo() == categoryNo) {
                p.printDetail();
                }
            }
            // 간소화 버전
            // if (p != null && p.getCat().get() == categotyNo) {
            // p.printDatil();
            // }
        }
    }
}​

 

import java.util.Scanner;

public class MallApp {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    MallService mall = new MallService();

        for (;;) {
            System.out.println("1. 카테고리 등록 2. 카테고리 출력 3. 상품등록 4. 상품출력 5. 카테고리별 상품출력 0. 종료");
            System.out.print("메뉴 선택> ");
            int selectNo = scanner.nextInt();

            if (selectNo == 1) {
                // 1. 번호와 이름을 입력받는다.
                // 2. Category객체를 생성한다.
                // 3. Category객체의 setter를 사용해서 값을 저장한다.
                // 4. MallService(위에서 생성한 mall리모콘)의 addCategory메소드에게 Category객체를 전달한다.
                System.out.print("번호입력> ");
                int no = scanner.nextInt();
                System.out.print("이름입력> ");
                String name = scanner.next();
            
                Category cat = new Category();

                cat.setNo(no);
                cat.setName(name);
            
                mall.addCategory(cat);

            } else if (selectNo == 2) {
                //System.out.println("카테고리 출력");
                mall.printAllCategories();

            } else if (selectNo == 3) {
                // 1. 카테고리 번호, 상품 번호, 상품 이름, 가격을 입력받는다.
                // 2. Product객체를 생성한다.
                //    Product객체의 setter를 사용해서 상품번호, 이름, 가격을 저장한다.
                //    MallService(위에서 생성한 mall리모콘)의 getCategory메소드에게 1번에서 입력받은 카테고리 번호를
                //      전달해서 번호에 해당하는 Category를 제공받는다.
                // 3. Product객체를 생성한다.
                // 4. Product객체의 setter를 사용해서 상품번호, 이름, 가격, 2번에서 획득한 Category객체를 저장한다.
                // 5. MallService(위에서 생성한 mall리모콘)의 addProduct메소드에게 Product객체를 전달한다.
                System.out.print("카테고리 번호 입력> ");
                int catNo = scanner.nextInt();
                System.out.print("상품 번호 입력> ");
                int proNo = scanner.nextInt();
                System.out.print("상품 이름 입력> ");
                String proName = scanner.next();
                System.out.print("상품 가격 입력> ");
                int proPrice = scanner.nextInt();

                Category c = mall.getCategory(catNo);

                Product product = new Product();
                product.setNo(proNo);
                product.setName(proName);
                product.setPrice(proPrice);
                product.setCat(c);

                mall.addProduct(product);

            } else if (selectNo == 4) {
                mall.printAllProducts();

            } else if (selectNo == 5) {
                System.out.print("카테고리 번호입력> ");
                int catNo = scanner.nextInt();

                mall.printProductsByCategory(catNo);

            } else if (selectNo == 0) {
                System.out.println("프로그램 종료");
                break;
            }
        }
    
    }
}
​

'자바 > oop5' 카테고리의 다른 글

Student, Printer, DatabaseAccess, Member.java  (0) 2019.06.07
public class Score {
    private int kor;
    private int eng;
    private int math;

    public Score() {}

    public Score(int kor, int eng, int math) {
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }

    public int getKor() {
        return kor;
    }

    public void setKor(int kor) {
        this.kor = kor;
    }

    public int getEng() {
        return eng;
    }

    public void setEng(int eng) {
        this.eng = eng;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }
}
​

 

public class Student {
    private int no;
    private String name;
    private Score score;    // Student has a Score (포함 관계)

    public Student() {}

    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Score getScore() {
        return score;
    }
    public void setScore(Score score) {
        this.score = score;
    }

}​

 

public class StudentApp {
    public static void main(String[] args) {
    
        // 1. 학생 정보를 저장하는 Student 객체 생성
        // 2. 그 학생의 성적 정보를 담는 Score 객체 생성
        // 3. 1번에서 생성된 Student객체에 성적 정보를 담고 있는 Score객체 전달(Setter 사용)
    
        Student s1 = new Student();
        s1.setNo(10);
        s1.setName("홍길동");

        Score s2 = new Score();
        s2.setKor(100);
        s2.setEng(70);
        s2.setMath(70);

        // Student 객체의 score필드에 Score객체 연결
        s1.setScore(s2);
    
        // 값 출력해보기

        int 번호 = s1.getNo();
        String 이름 = s1.getName();
        /*
        Score 점수 = s1.getScore();
        int 국어 = 점수.getKor();
        int 영어 = 점수.getEng();
        int 수학 = 점수.getMath();
        */

        int 국어 = s1.getScore().getKor();    // 위와 같은 코드임
        int 영어 = s1.getScore().getEng();
        int 수학 = s1.getScore().getMath();

        System.out.println(번호);
        System.out.println(이름);
        System.out.println(국어);
        System.out.println(영어);
        System.out.println(수학);

    }
}​

 

public abstract class Printer{

    public void on() {
        System.out.println("전원 켜기");
    }

    public void off() {
        System.out.println("전원 끄기");
    }

    public void feed() {
        System.out.println("용지 공급하기");
    }
    
    // 추상 메소드 정의
    // 모든 프린터들이 가지고 있는 출력기능(프린터마다 구현 내용이 다를 것으로 예상)을
    // void print()라는 추상 메소드로 추상화함으로써
    // 모든 프린터들이 출력 기능은 void print() {구체적인 구현내용}로 통일되게 정의하게 만듦
    public abstract void print();
}
​

 

public class ColorPrinter extends Printer {
    // Printer 클래스에 정의된 추상 메소드 재정의
    public void print() {
        System.out.println("컬러로 출력합니다.");
    }
    // ColorPrinter의 고유기능
    public void photo() {
        System.out.println("고품질 사진을 출력합니다.");
    
    }
}​

 

public class BlackAndWhitePrinter extends Printer {

    // Printer로부터 상속받은 추상메소드를 구체적인 구현 내용을 가진 메소드로 만든다.
    public void print() {
        System.out.println("흑백으로 출력합니다.");
    }

}
​

 

public class PrinterApp {
    public static void main(String[] args) {
        // 추상 클래스는 new 키워드를 사용해서 객체 생성 할 수 없다.
        // Printer p1 = new Printer();    <--에러

        BlackAndWhitePrinter p2 = new BlackAndWhitePrinter();
        p2.on();
        p2.feed();
        p2.print();
        p2.off();

        Printer p3 = new BlackAndWhitePrinter();
        p3.on();
        p3.feed();
        p3.print();
        p3.off();

        ColorPrinter p4 = new ColorPrinter();
        p4.on();
        p4.feed();
        p4.print();
        p4.off();

        Printer p5 = new ColorPrinter();
        p5.on();
        p5.feed();
        p5.print();
        p5.off();

    }
}​

 

public abstract class DatabaseAccess {
    public void connect() {
        System.out.println("데이터베이스와 연결");
    }
    public void send() {
        System.out.println("데이터베이스에 쿼리문 전송");
    }

    public void receive() {
        System.out.println("데이터베이스로부터 데이터 획득");
    }

    public void disconnect() {
        System.out.println("데이터베이스와 연결 해제");
    }
    
    public abstract void display();

    public void access() {
        connect();
        send();
        receive();
        disconnect();
        display();
    }
}
​

 

public class 성적조회 extends DatabaseAccess {
    public void display() {
        System.out.println("조회된 정보를 성적표에 표시합니다.");
    }
}
​

 

public class 출석부조회 extends DatabaseAccess {
    public void display() {
        System.out.println("조회된 정보를 출석부에 표시합니다.");
    }
}
​

 

public class DatabaseAccessApp {
    public static void main(String[] args) {
        출석부조회 a = new 출석부조회();
        a.access();
    }
}
​

 

public interface MemberService {

    // 추상 메소드
    public abstract void removeAllMemebers();

    //public abstract는 생략가능하다.
    public abstract void printAllMembers();

    public abstract void removeMemberByNo(int no);

    public abstract String getMemberNameByNo(int no);
}
​

 

public class MemberServiceImpl implements MemberService {

    public void removeAllMemebers() {
        System.out.println("엑셀파일에서 모든 회원 정보를 삭제한다.");
    }

    public void printAllMembers() {
        System.out.println("엑셀파일의 모든 회원정보를 출력한다.");
    }

    public void removeMemberByNo(int no) {
        System.out.println("엑셀파일에서 " + no + "번 회원을 삭제한다.");
    }

    public String getMemberNameByNo(int no) {
        String name = null;
        name = "홍길동";
        System.out.println("엑셀파일에서 " + no + "번 회원의 이름을 조회한다.");
        return name;
    }
}​

 

public class MemberApp {
    public static void main(String[] args) {
        //MemberService 인터페이스를 구현한 객체 생성
        MemberServiceImpl service1 = new MemberServiceImpl();
        service1.printAllMembers();

        // 인터페이스를 구현한 객체는 인터페이스 타입의 변수에 담을 수 있다.
        MemberService service2 = new MemberServiceImpl();
    }
}​

'자바 > oop5' 카테고리의 다른 글

Car, HRMgr, Mall.java  (0) 2019.06.07

+ Recent posts