본문 바로가기
Study/Java

[Java] 인터페이스와 추상클래스

by JYHAN 2020. 7. 3.

인터페이스란?  - 추상화의 꽃, 추상 method들의 집합

 

클래스와 달리 객체를 생성할 수 없으며, 클래스에서 구현해야 하는 작업 명세서

반드시 interface에 있는 abstract method를 상속받은 클래스에서 구현해야 한다

인터페이스와 클래스

인터페이스를 사용하는 이유

인터페이스를 사용하는 이유는 많지만, 가장 큰 이유는 객체가 다양한 자료형(타입)을 가질 수 있기 때문이다

 

인터페이스 구현

public interface InterfaceA {
	public void funA();
}

public interface InterfaceB {
	public void funB();
}

public class MainClass {
	public static void main(String[] args) {
		InterfaceA ia = new InterfaceClass();
		InterfaceB ib = new InterfaceClass();
		
		ia.funA();
		ib.funB();
	}
}

---- result ----
IC Constructor
IC Constructor
 -- funA() --
 -- funB() --

ia는 InterfaceClass를 이용해서 객체를 생성했지만, 타입InterfaceA 라서 funA() 메서드만 사용할 수 있다

같은 이유로 ib는 funB() 메서드만 사용할 수 있다

 

장난감 인터페이스

public interface Toy {
	public void walk();
	public void fly();
}

public class ToyAirplane implements Toy {
	@Override
	public void walk() {
		System.out.println("Airplane can not walk");
	}

	@Override
	public void fly() {
		System.out.println("Airplane can fly");
	}
}

public class ToyRobot implements Toy{
	@Override
	public void walk() {
		System.out.println("Robot can walk");
	}

	@Override
	public void fly() {
		System.out.println("Robot can not walk");
	}
}

public static void main(String[] args) {
	Toy airplane = new ToyAirplane();
	Toy robot = new ToyRobot();
	
	// 배열에는 한 가지 타입만 들어갈 수 있다, 타입->Toy
	Toy toys[] = {robot, airplane};
	
	for(int i=0; i<toys.length; i++) {
		toys[i].fly();
		toys[i].walk();
		System.out.println();
	}
}

---- result ----
Robot can not walk
Robot can walk

Airplane can fly
Airplane can not walk

 

 

추상(Abstract) 클래스 란?

클래스의 공통된 부분을 뽑아서 별도의 클래스(추상 클래스)로 만들어 놓고, 이것을 상속해서 사용한다

추상클래스와 클래스

추상 클래스의 특징

  • 멤버 변수를 가진다
  • abstract 클래스를 상속하기 위해서는 extends를 사용한다
  • abstract 메서드를 가지며, 상속한 클래스에서 반드시 구현해야 한다
  • 일반 메서드도 가질 수 있다
  • 일반 클래스와 마찬가지로 생성자도 있다

추상 클래스 구현

public abstract class AbstractClass {
	int num;
	String str;
	public AbstractClass() {
		System.out.println("AbstractClass Constructor!");
	}
	public AbstractClass(int n, String s) {
		System.out.println("AbstractClass Constructor!!!");
		this.num = n;
		this.str = s;
	}
	public void fun1() {
		System.out.println("--- fun1() Start");
	}
	public abstract void fun2();
}

public class ClassEx extends AbstractClass {
	public ClassEx(int n, String s) {
		super(n,s);
		System.out.println("ClassEx Constructor!!!");
	}
	
	@Override
	public void fun2() {
		// TODO Auto-generated method stub
		System.out.println("--- fun2() Start ---");
	}
}

public class MainClass {
	public static void main(String[] args) {
		AbstractClass ab = new ClassEx(10, "java");
		ab.fun1();
		ab.fun2();
	}
}


---- result ----
AbstractClass Constructor!!!
ClassEx Constructor!!!
--- fun1() Start
--- fun2() Start ---

 

인터페이스와 추상클래스 차이

인터페이스 추상클래스
공통점
추상 메서드를 가진다
객체 생성이 불가하며 자료형(타입)으로 사용된다
차이점
상수, 추상메서드만 가진다
추상 메서드를 구현만 하도록 한다
다형성을 지원한다
클래스가 가지는 모든 속성과 기능을 가진다
추상 메서드 구현 및 상속의 기능을 가진다
단일 상속만 지원한다

 

댓글