추상 메서드는 메서드의 본체가 완성되지 않은 미완성 메서드
를 말한다. 추상 메서드를 1개 이상 포함하고 있는 클래스는 반드시 추상 클래스로 정의되어야 한다.
abstract class Shape{
int x,y;
//추상 클래스라고 하더라도 추상 메소드가 아닌 보통의 메소드도 가질 수 있다!
public void translate(int x, int y){
this.x=x;
this.y=y;
}
//추상 메소드를 선언
public abstract void draw();
};
class Rectangle extends Shape{
int width,height;
//자식 클래스 Rectangle에서 부코 클래스의 추상메소드 draw()를 직접 구현한다.
public void draw(){
System.out.println("사각형 그리기 메소드");}
};
class Circle extends Shape{
int radius;
//자식 클래스 Rectangle에서 부코 클래스의 추상메소드 draw()를 직접 구현한다.
public void draw(){
System.out.println("삼각형 그리기 메소드");}
};
인터페이스는 내부의 모든 필드가 public static final로 정의되고, static과 default 메서드 이외의 모든 메서드는 public abstract로 정의된 객체지향 프로그래밍 요소다. class 대신 interface 키워드를 사용하여 선언한다.
interface 인터페이스명{
public static final 자료형 필드명 = 값;
public abstract 리턴 타입 메서드명 ();
}
예시
interface A public static final int a = 3; public abstract void abc(); }
//인터페이스의 정의
//메소드의 몸체를 갖지 않는다 따라서 인스턴스 생성 불가하고 참조변수 선언은 가능하다.
interface Printable{
public void print(String doc);
}
//인터페이스를 구현하는 클래스
//구현하는 메소드와 추상 메소드 사이에도 메소드 오버라이딩 관계 성립
class Printer implements Printable{
public void print(String doc){
System.out.println(doc);
}
}