TIL/남궁성의 자바의 정석
자바의 정석 ch7-35~37 인터페이스의 선언, 상속, 구현
minOE
2024. 1. 2. 23:55
728x90
ch7-35 인터페이스(interface)
- 추상 메서드의 집합
- 구현된 것이 전혀 없는 설게도 , 껍데기 (모든 멤버가 public)
interface 인턴페이스이름{ public static final 타입 상수이름 = 값; public abstract 메서드 이름 (매개변수 목록); }
예시
interface playingCard{ public static final int SPACE =4; /* 4개의 상수 모두 public static final int 생략, 인터페이스에서 예외 없음*/ final int DIAMOND =4; static int HEART=2; int CLOVER=1; public abstract String getCardNumber(); String getCardkind(); // public abstract 생략 (인터페이스의 모든 메서드는 public이고 abstract이다.) }
ch7-36 인터페이스 상속
- 인터페이스의 조상은 인터페이스만 가능 (추상 클래스처럼 Object가 최고 조상 아님 )
- 다중 상속이 가능(추상 메서드는 충돌해도 문제 없음)
* 추상 클래스가 다중 상속이 힘든이유
: 선언부가 같고 구현부가 다르면 어느 쪽을 상속 받을지 결정할 수 없기 때문이다.
interface Fightable extends Movable,Attackable{} abstract class Unit{ int x,y; abstract void move(int x, int y); void stop(){/* 현재 위치에서 정지*/} } interface Movable{ /* 지정된 위치로( x,y)로 이동하는 기능의 메서드 */ void move(int x, int y); } interface Attackable{ /* 지정된 대상(u)을 공격하는 기능의 메서드 */ void attack(Unit u); } public class Main { public static void main(String[] args) { System.out.println("인터페이스 상속"); } }
ch7-37 인터페이스의 구현
- 인터페이스에 정의된 추상 메서드를 완성하는 것
class 클래스이름 implements 인터페이스이름{ // 인터페이스에 정의된 추상 메서드를 모두 구현해야한다. }
예시interface Fightable { public void move(int x, int y); public void attack(Unit u); } abstract class Unit{ int x,y; abstract void move(int x, int y); } class Fighter implements Fightable{ public void move(int x, int y) { /* 내용생략*/} public void attack(Unit u) {/* 내용생략*/} } public class Main { public static void main(String[] args) { System.out.println("인터페이스의 구현"); } }
- 인터페이스의 일부만 구현하는 경우 , 클래스 앞에 abstract 붙여야함interface Fightable { public void move(int x, int y); public void attack(Unit u); } abstract class Unit{ int x,y; abstract void move(int x, int y); } // 인터페이스의 일부만 구현하는 경우 abstract class Fighter implements Fightable { public void move(int x, int y) { /* 내용생략 */} } public class Main { public static void main(String[] args) { System.out.println("인터페이스의 일부 구현"); } }
위 코드와 아래 코드는 같은 코드이다.interface Fightable { public void move(int x, int y); public void attack(Unit u); } abstract class Unit{ int x,y; abstract void move(int x, int y); } // 인터페이스의 일부만 구현하는 경우 abstract class Fighter implements Fightable { public void move(int x, int y) { /* 내용생략 */} public abstract void attack(Unit u) ; } public class Main { public static void main(String[] args) { System.out.println("인터페이스의 일부 구현"); } }
정리
Q.인터페이스란 ?
A.추상 메서드 집합 (JDK 1.8부터 상수, static메서드,디폴트 메서드 추가)
Q.인터페이스 구현이란 ?
A. 인터페이스의 추상메서드 구현부 만드는 것 , 즉 미완성 설계도 완성하기
Q.추상클래스와 인터페이스 공통점
A. 추상메서드를 가지고 있다(미완성 설계도)
Q.추상클래스와 인터페이스 차이점
A. 추상클래스와 달리 인터페이스는 인스턴스변수 , 생성자, 인스턴스 메서드를 가질 수 없다. 인터페이스는 구현이 전혀 없고 껍데기만 있다.
728x90