자바에서 일종의 설계도로 클래스가 인터페이스를 implements하면,
인터페이스에 정의된 모든 메서드를 반드시 구현해야 함
interface 인터페이스명 {
추상 메서드();
}
// 몸체가 없는 추상 메서드 구현
// 구현하는 클래스에서 반드시 구현해야 함
class Dog implements Animal {
public void sound() {
System.out.println("멍멍");
}
// implements 키워드를 반드시 사용해야 함
// 인터페이스의 모든 메서드를 반드시 오버라이딩
// 인터페이스의 모든 메서드는 자동으로 public abstract으로
// 선언되어 반드시 메서드 선언 시 앞에 public을 붙여야 함
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("꽥꽥");
}
}
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);
}
}