You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
public abstract class Animal {
String name; // 멤버 변수
public void setName(String name) { // 멤버 함수
this.name = name;
}
public abstract void breathing();
// public void breathing() {}; 의 경우 구현부를 선언하였기 때문에, 추상 메소드가 아니다.
public void eating(String feed) {
System.out.println(name + " eat " + feed);
}
}
추상 메소드
함수의 실제 구현부를 선언(정의)하지 않고, 함수의 이름만을 선언한 메소드를 의미한다.
추상 클래스는 함수의 선언부에 abstract 키워드를 붙여 선언한다.
추상 메소드의 경우 자식 클래스(상속받는 클래스)가 반드시 구현해야 한다.
public void abstractMethod();
public abstract void absKeyMethod();
추상 클래스의 구현
abstract class Animal {
private String name; // 멤버 변수
public void setName(String name) { // 멤버 함수
this.name = name;
}
public abstract void breathing();
// public void breathing() {}; 의 경우 구현부를 선언하였기 때문에, 추상 메소드가 아니다.
public void eating(String feed) {
System.out.println(name + " eat " + feed);
}
}
public class Dog extends Animal{
public void breathing() {
System.out.println("Dog is breathing");
}
}
public class AbstractTest {
public static void main(String[] args) {
Dog dog = new Dog();
dog.setName("Any");
dog.breathing();
dog.eating("meat");
}
}
Tip. 추상 클래스 및 추상 메소드의 경우 클래스 다이어그램에서 이탤릭체로 표현된다.
인터페이스
클래스가 구현해야 하는 동작들을 지정하는 기본 틀을 의미한다.
interface 키워드를 사용하여 선언한다.
멤버 변수 및 멤버 함수를 선언할 수 없다.
(추상 메소드와 상수만을 포함(선언)할 수 있다.)
인터페이스를 상속받는 클래스는 implements키워드를 통해 인터페이스들을 상속받을 수 있다.
(인터페이스는 추상 클래스와는 달리 다중 상속을 지원한다.)
Java의 다형성을 극대화하여 코드의 유지보수성을 높일 수 있다.
public interface HelloBot{
public String printHello();
}
public class InterfaceTest implements Hellobot {
public String printHello() {
System.out.println("Hello");
}
}
※ 추상 클래스와 인터페이스의 차이점
추상 클래스의 경우 일반 메소드 및 멤버 변수 등을 가질 수 있지만, 인터페이스의 경우 멤버 변수 및 멤버 메소드를 가질 수 없다.
추상 클래스의 경우 하나만 상속(extends)이 가능하지만, 인터페이스의 경우 다중 상속이 가능하다.(implements)
// Abstract Class
abstract class WritingBot {
public String printName(String name);
}
abstract class ReadingBot {
public String readName(String name);
}
public class AbsWritingBot extends WritingBot{
public String printName(String name) {
return "Print" + name;
}
}
public class AbsReadingBot extends ReadingBot{
public String readName(String name) {
return "Read" + name;
}
}
// 다음과 같이 선언하는 경우
// Class cannot extend multiple classes 라는 에러가 발생한다.(IntelliJ 기준)
public class AbsWritingBot extends WritingBot, RadingBot {
public String readName(String name) {
return "Read" + name;
}
public String printName(String name) {
return "Print" + name;
}
}
// Interface
public interface WritingBot {
public String printName(String name);
}
public interface ReadingBot {
public String readName(String name);
}
public InterBot implements WritingBot, ReadingBot {
public String readName(String name) {
return "Read" + name;
}
public String printName(String name) {
return "Print" + name;
}
}