관리 메뉴

너와 나의 스토리

[Java] 추상 클래스 / 인터페이스 본문

Programming Language/Java

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

노는게제일좋아! 2021. 4. 13. 10:16
반응형

Abstract(추상)

  • 실체 간의 공통되는 특성을 추출한 것
  • 예: 새, 곤충, 물고기 등의 실체에서 공통되는 특성 -> 동물

 

추상 클래스

public abstract class ClassName {
    // 필드
    
    // 생성자
    
    // 메서드
}
  • 추상 클래스는 new 연산자를 이용해서 객체를 만들지 못하고 상속을 통해 자식 클래스만 만들 수 있다.
  • 예:
public abstract class Animal {
    public String kind;
    
    public Animal(String kind){
        this.kind = kind;
    }
    
    public void sound(){
        System.out.println("동물이 내는 소리");
    }
}

public class Dog extends Animal {

    public Dog(String kind){
      	super(kind);
    }
    
}

public static void main(String[] args) {
    //Animal animal = new Animal();  -> 객체 생성 불가
    
    Dog dog = new Dog();
    dog.sound();
}

 

 

추상 메서드    

  • 위의 예를 다시 보자.
  • Animal 추상 클래스에는 sound()이라는 메서드가 있다.
    • 동물마다 내는 소리가 다르다. 이런 경우 각 실체 클래스에서 sound() 메서드를 정의해서 사용해야 한다.
    • 그렇다고, 추상 클래스에서 sound() 메서드를 없애버리면, 실체 클래스 작성자 이 메서드를 잊어버릴 수도 있고, 메서드 이름을 다르게 사용할 수도 있다.
    • 이런 경우 abstract method를 사용할 수 있다.
  • Abstract method의 경우 {구현 내용}이 없이 선언만 해준다.
    • 아래의 예시처럼 사용하면 된다.
public abstract class Animal {
    public String kind;
    
    public Animal(String kind){
        this.kind = kind;
    }
    
    public abstract void sound();
}

public class Dog extends Animal {

    public Dog(String kind){
      	super(kind);
    }
    
    @Override
    public void sound(){
      	System.out.println("왈왈왈");    
    }
}

 

 

 

Interface

  • 객체의 사용 방법을 정의한 타입.
public interface interfaceName {
  // Constant Field

  // Abstract Method

  // Default Method

  // Static Method
}
  • Constant Field(상수 필드)
    • 인터페이스는 런타임 시 데이터를 저장할 수 있는 필드를 가질 수 없다. 하지만, 상수 필드는 선언할 수 있다.
  • Abstract Method(추상 메서드)
  • Default Method(디폴트 메서드)
    • 구현 코드를 포함한 메서드
    • 구현 객체에서 호출해서 사용
    • 사용법: default (Type) methodName() {...}
  • Static Method(정적 메서드)
    • 객체가 없어도 인터페이스만으로 호출이 가능.

 

 

Default Method 필요성

public interface MyInterface {
    public void method1();

    public default void method2() {
    
    }
}

public class MyClassA implements MyInterface {
    public void method1();
}

public class MyClassB implements MyInterface {
    public void method1();
    public void method2();
}
  • MyInterface에 새로운 기능(method2)을 추가할 일이 생겼다고 하자.
  • 이때, 추상 메서드로 method2()를 MyInterface에 추가하면 MyClassA에서 오류가 발생한다.
  • 하지만 method2를 default 메서드로 선언해주면, MyClassA에서 에러가 발생하지 않고, MyClassB는 (MyInterface에서 정의한) method2()를 그대로 사용하거나, 재정의해서 사용할 수 있다.

 

 

Interface 상속

  • 인터페이스는 클래스와 달리 다중 상속을 허용한다.
public interface InterfaceA {
	public void methodA();
}

public interface InterfaceB {
	public void methodB();
}

public interface InterfaceC {
	public void methodC();
}

public class ImplementationC implements InterfaceC {
	public void methodA() {}
	public void methodB() {}
	public void methodC() {}
}

 

 

추상 클래스 vs 인터페이스

  • 두 클래스의 목적: 설계도 -> 상속을 통해 자식 클래스를 구현하도록 유도
  • 추상 클래스
    • 역할:
      • 구현 클래스들의 공통된 필드와 메서드의 이름을 통일할 목적
      • 구현 클래스를 작성할 때 시간을 절약
    • new 연산자로 객체 생성 불가
    • 단일 상속만 가능
  • 인터페이스
    • 역할:
      •  개발 코드가 객체의 내부 구조를 알 필요 없고 인터페이스의 메서드만 알고 있어도 된다.
        • 즉, 개발 코드를 수정하지 않고, 사용하는 객체를 변경할 수 있다.
    • new 연산자로 객체 생성 불가
    • 다중 상속 가능

 

 

 

 

출처:

- [이것이 자바다]

반응형
Comments