[JAVA] interface

장성욱·2025년 7월 9일

JAVA

목록 보기
21/23

인터페이스 (interface)

자바에서 일종의 설계도로 클래스가 인터페이스를 implements하면,
인터페이스에 정의된 모든 메서드를 반드시 구현해야 함

사용하는 목적

  1. 개발자 간의 약속
  2. 다형성 => 인터페이스 타입으로 여러 구현 객체를 처리 가능
  3. 결합도 낮추기 => 객체들 간 연결을 느슨하게 만들어 유지보수 유리

기본 문법

interface 인터페이스명 {
	추상 메서드();
}
// 몸체가 없는 추상 메서드 구현
// 구현하는 클래스에서 반드시 구현해야 함

class Dog implements Animal {
	public void sound() {
    	System.out.println("멍멍");
}
// implements 키워드를 반드시 사용해야 함
// 인터페이스의 모든 메서드를 반드시 오버라이딩

// 인터페이스의 모든 메서드는 자동으로 public abstract으로 
// 선언되어 반드시 메서드 선언 시 앞에 public을 붙여야 함

유용 문제

1번 )
class Main {
  public static void main(String[] main) {
    Soundable[] animals = {new Dog(), new Cat(), new Duck()};

    for (Soundable s : animals) {
      s.sound();
    }
  }
}
interface Soundable {
  void sound();
}
class Dog implements Soundable {
  public void sound() {
    System.out.println("멍멍");
  }
 }
class Cat implements Soundable {
  public void sound() {
    System.out.println("야옹");
  }
}
class Duck implements Soundable {
  public void sound() {
    System.out.println("꽥꽥");
  }
}
2번 )
import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("면적을 구할 도형을 입력해 주세요 :");
    String shape = sc.nextLine();

    if (shape.equals("원")) {
      System.out.print("원의 반지름을 입력해 주세요 : ");
      int r = sc.nextInt();
      sc.nextLine();
      Circle c = new Circle(r);
      c.cal();
    }
    else if (shape.equals("삼각형")) {
      System.out.print("삼각형의 밑변 길이를 입력해 주세요 : ");
      int u = sc.nextInt();
      sc.nextLine();

      System.out.print("삼각형의 높이를 입력해 주세요 : ");
      int h = sc.nextInt();
      sc.nextLine();

      Triangle t = new Triangle(u, h);

      t.cal();
    } else {
      System.out.println("원, 삼각형만 가능합니다.");
    }

  }
}
interface Shape {
  void cal();
}
class Circle implements Shape {
  int r;
  Circle(int r) {
    this.r = r;
  }
  public void cal () {
    System.out.println("면적 : " + 3.14 * r * r);
  }
}
class Triangle implements Shape {
  int u;
  int h;
  Triangle (int u, int h) {
    this.u = u;
    this.h= h;
  }
  public void cal () {
    System.out.println("면적 : " + u * h /2);
  }
}
profile
https://frost-puck-b0f.notion.site/B-2610fdaef71d80c49d1bccdcb575dcb5

0개의 댓글