본문 바로가기
풀스택/Java다시 복습 처음부터

java 복습 3-5(객체지향 프로그래밍) - 인터페이스

by woohyun22 2019. 6. 6.
1
2
3
4
5
6
7
public class Animal {
    String name;
 
    public void setName(String name) {
        this.name = name;
    }
}
cs


1
2
3
4
5
6
7
public class Tiger extends Animal {
 
}
 
public class Lion extends Animal {
 
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class ZooKeeper {
    public void feed(Tiger tiger) {
        System.out.println("feed apple");
    }
 
    public void feed(Lion lion) {
        System.out.println("feed banana");
    }
 
    public static void main(String[] args) {
        ZooKeeper zooKeeper = new ZooKeeper();
        Tiger tiger = new Tiger();
        Lion lion = new Lion();
        zooKeeper.feed(tiger);
        zooKeeper.feed(lion);
    }
}
cs


위처럼 계속 오버로딩을 하면 동물 한마리 마다 새로 메소드를 만들어주어야되는데 계속 반복되는 오버로딩을 편하게 쓰기 위해 인터페이스를 쓴다. 


implements 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface Predator {
 
}
 
public class Tiger extends Animal implements Predator {
 
}
 
public class Lion extends Animal implements Predator {
 
}
 
public void feed(Predator predator) {
    System.out.println("feed apple");
}
cs



1
2
3
public interface Predator {
    public String getFood();
}
cs



1
2
3
4
5
public class Tiger extends Animal implements Predator {
    public String getFood() {
        return "apple";
    }
}
cs


1
2
3
4
5
public class Lion extends Animal implements Predator {
    public String getFood() {
        return "banana";
    }
}
cs


1
2
3
4
5
public class ZooKeeper {    
    public void feed(Predator predator) {
        System.out.println("feed "+predator.getFood());
    }
}
cs


오버로딩을 해서 만들었던 feed 메소드를 하나로 묶고, 동물들을 인터페이스화해서 만들었다. 인터페이스에도 메소드를 추가했다.


알아보기 쉽게 정리한 표


물리적세계자바세계
컴퓨터ZooKeeper
USB 포트Predator
하드디스크, 디지털카메라,...Tiger, Lion, Crocodile,...


728x90

댓글