Java
인터페이스
Namlulu
2023. 7. 27. 13:19
728x90
인터페이스를 활용하면 객체지향을 조금 더 편리하게 구현할 수 있다.
public interface Car {
void move();
}
public class FastCar implements Car {
@Override
public void move() {
System.out.println("빠르게 달립니다.");
}
}
public class SnowCar implements Car {
@Override
public void move() {
System.out.println("겨울에 잘 달립니다.");
}
}
public class SuperCar implements Car {
@Override
public void move() {
System.out.println("슈퍼하게 달립니다.");
}
}
- 인터페이스를 통해, 다형성과 추상화를 구현한 사례이다.
public interface LivingBeing {
void grow();
void reproduce();
void die();
}
public interface Animal extends LivingBeing {
void makeSound();
}
public class Dog implements Animal {
@Override
public void grow() {
System.out.println("The dog is growing.");
}
@Override
public void reproduce() {
System.out.println("The dog is reproducing.");
}
@Override
public void die() {
System.out.println("The dog has died.");
}
@Override
public void makeSound() {
System.out.println("Woof woof!");
}
// Additional member variables and methods specific to dogs can be defined here.
}
- 인터페이스는 상속도 가능하다.
- 클래스랑 달리, 다중 상속도 가능하다.
public interface LivingBeing {
void grow();
void reproduce();
void die();
}
public interface Animal extends LivingBeing {
void makeSound();
}
public class Dog implements Animal {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void grow() {
System.out.println(name + " the dog is growing.");
}
@Override
public void reproduce() {
System.out.println(name + " the dog is reproducing.");
}
@Override
public void die() {
System.out.println(name + " the dog has died.");
}
@Override
public void makeSound() {
System.out.println(name + " the dog says: Woof woof!");
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
public class Cat implements Animal {
private String name;
private int age;
public Cat(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void grow() {
System.out.println(name + " the cat is growing.");
}
@Override
public void reproduce() {
System.out.println(name + " the cat is reproducing.");
}
@Override
public void die() {
System.out.println(name + " the cat has died.");
}
@Override
public void makeSound() {
System.out.println(name + " the cat says: Meow meow!");
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
- 고양이 사례도 추가되었고, 이름과 나이를 직접 접근하지 않고도 캡슐화를 통해 메서드로 파악할 수 있다.
300x250