Java 추상클래스 - java chusangkeullaeseu

이 포스팅에는 아래의 내용이 포함되어있습니다.

1. 추상클래스

2. 추상 메서드

3. 예제

1. 추상클래스란?(abstract class)

- 추상메서드를 1개 이상 가지고 있는 클래스

- 추상메서드는 선언부만 있고 구현부는 없는 클래스

- 완성된 설계도가 아니기 때문에 인스턴스를 생성할 수 없다.

- 인스턴스를 생성하기 위해서는 추상메서드를 구현해야한다.

- 다른 클래스를 작성하는데 도움을 줄 목적으로 작성된다.

2. 추상 메서드

- 선언부만 있고 구현부는 없는 클래스

- 꼭 필요하지만 자손마다 다르게 구현 될 것으로 예상되는 경우 사용

- 추상 클래스의 일부 메서드만 구현할 때 그 클래스 앞에 abstract를 붙여야한다.

예제를 통해 살펴보겠습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package sec01_exam;

//추상클래스란? 

//추상메서드를 한개이상 포함하는 클래스

//추상클래스는 인스턴스를 생성할 수 없다.

public abstract class ContentSender {

String title;

String nm;

public ContentSender() {

// TODO Auto-generated constructor stub

}

public ContentSender(String title, String nm) {

super();

this.title = title;

this.nm = nm;

}

//추상메서드 --> 상속을 통해서 반드시 재정이 되어야지만 비로소 인스턴스를 생성할 수 있다. 

public abstract void sendMsg(String content);

}

cs

 ContentSender은 추상 클래스 입니다.

abstract가 붙었고

추상 메서드인 sendMsg가 포함되어있습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

package sec01_exam;

public class KakaoSender extends ContentSender{

String content;

public KakaoSender(String title, String nm, String content) {

super(title, nm);

this.content = content;

}

@Override

public void sendMsg(String recipient) {

System.out.println("제목=" + this.title);

System.out.println("이름=" + this.nm);

System.out.println("내용=" + this.content);

System.out.println("받는 사람=" + recipient);

}

}

cs

클래스 KakaoSender에서 추상 클래스인 ContentSender을 상속받았습니다.

그러면 추상메서드를 구현해야합니다.

오버라이딩하여 구현을 해주었습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package sec01_exam;

public class letterSender extends ContentSender{

String content;

public letterSender(String title, String nm, String content) {

super(title, nm);

this.content = content;

}

//조상클래스인 ContentSender추상클래스의 추상메서드인 sendMsg()를 오버라이딩(구현부 존재함)함.

@Override

public void sendMsg(String recipient) {

System.out.println("제목=" + this.title);

System.out.println("이름=" + this.nm);

System.out.println("내용=" + this.content);

System.out.println("받는 사람=" + recipient);

}

}

cs

letterSender클래스도 마찬가지입니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

package sec01_exam;

public class SenderEx {

public static void main(String[] args) {

//추상 클래스는 인스턴스를 절대로 생성하지 못한다. 

//ContentSender contentSender = new ContentSender();

//예외 발생 이유? ContentSender가 추상클래스라서 추상메서드를

//자손에서 오버라이딩 해주어야 인스턴스가 생성된다.

ContentSender cs1 = new letterSender("SMS문자""서수진""4달라"); //필드의 다형성

cs1.sendMsg("슈화");

System.out.println();

letterSender ls = new letterSender("SMS문자""김민니""3달라");

ls.sendMsg("조미연");

System.out.println();

ContentSender cs2 = new KakaoSender("카톡""송우기""10달라");

cs2.sendMsg("전소연");

}

}

cs

실행클래스입니다.

필드의 다형성으로 ContentSender을 자손의 클래스들로 생성을 하고 있습니다.

그리고 구현해준 추상 메서드를 호출합니다.

<출력결과>

Java 추상클래스 - java chusangkeullaeseu

두번째 예제입니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public abstract class Unit {

//필드

int x;

int y;

String str;

//추상메서드 선언(구현부 없다.)

//모든 유닛은 움직여야하기 때문에 move()를 추상메서드로 썼다.

public abstract void move(int x, int y);

public void stop(String str, int x, int y) {

this.x = x;

this.y = y;

this.str = str;

System.out.println("현재위치: " + this.x + "," + this.y +"에" + this.str + "가/이 멈춥니다.");

}

}

cs

추상 클래스 Unit을 만들어주었고 

추상 메서드 move를 만들었습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public class Tank extends Unit{

public Tank() {

}

@Override

public void move(int x, int y) {

System.out.println("탱크의 위치: " + x +"," + y + "로 이동함.");    

}

//Tank의 고유메서드

public void sizeMode(){

System.out.println("공격모드: 시즈모드 변환");

}

}

cs

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

public class Marine extends Unit{

public Marine() {

}

@Override

public void move(int x, int y) {

System.out.println("마린의 위치: " + x +"," + y + "로 이동함.");    

}

//Marine의 고유메서드

public void stimPack(){

System.out.println("공격모드: 스팀팩 장전!");

}

}

cs

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public class DropShip extends Unit{

public DropShip() {

}

@Override

public void move(int x, int y) {

System.out.println("드랍쉽의 위치: " + x +"," + y + "로 이동함.");    

}

//DropShip의 고유메서드

public void load(){

System.out.println("탑승모드: 유닛 탑승!");

}

public void unload(){

System.out.println("탑승모드: 유닛 하강!");

}

}

cs

Unit을 상속받은 클래스 3개를 만들어주었고 

move메서드는 각각 다르게 오버라이딩 해주었습니다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

public class UnitEx {

public static void main(String[] args) {

//Unit unit = new Unit(); //예외 발생 이유?

System.out.println("---------------------------------");

Tank tank = new Tank();

tank.move(100300);

tank.sizeMode();

tank.stop("탱크"300400);

System.out.println("---------------------------------");

Marine marine = new Marine();

marine.move(200500);

marine.stimPack();

marine.stop("마린"300400);

System.out.println("---------------------------------");

DropShip dp = new DropShip();

dp.move(500600);

dp.load();

dp.unload();

dp.stop("드랍쉽"200100);

}

}

cs

맨 위에 주석 처리 한 코드 예외 발생 이유는 무엇일까요?

Unit은 추상클래스이기 때문에 인스턴스를 생성할 수 없어서 예외가 발생합니다.

<실행결과>

Java 추상클래스 - java chusangkeullaeseu

Unit의 move메서드를 각각 오버라이딩했더니 객체마다 오버라이딩한 move메서드가 나타남을 확인할 수 있습니다.