Java/ Interface의 개념
Interface is a blueprint of a class. It has static constants and abstract methods.
The interface is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Why use Java interface?
- It is used to achieve abstraction.
- By interface, we can support the functionality of multiple inheritance.
- It can be used to achieve loose coupling.
인터페이스의 생김새는 클래스와 유사하지만 객체를 만들 수 없다. 그러나 인터페이스 형 변수와 배열은 선언 할 수 있다. 인터페이스와 이를 이용한 클래스를 사용하면 이해하기 쉬운 코드를 작성 할 수 있다.
- Literal 상수 : 숫자 1, 2, ...
- Constant 상수 : 변수 -> 상수(final) MON, TUE, ...
-인터페이스에 선언하는 필드는 자동으로 public final static이 붙는다.
public class SelectDayWeek {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("오늘의 요일을 선택하세요");
System.out.println("1.월요일, 2.화요일, 3.수요일");
System.out.println("4.목요일, 5.금요일, 6.토요일");
System.out.println("7.일요일");
System.out.print("번호 선택 : ");
int sel = sc.nextInt();
switch(sel) {
case IWeek.MON:System.out.println("주간회의 있습니다");break;
case IWeek.TUE:System.out.println("플젝회의 있습니다");break;
case IWeek.WED:System.out.println("진행보고 있습니다");break;
case IWeek.THU:System.out.println("축구시합 있습니다");break;
case IWeek.FRI:System.out.println("플젝발표 있습니다");break;
case IWeek.SAT:System.out.println("가족여행 떠납니다");break;
case IWeek.SUN:System.out.println("오늘은 휴일입니다");break;
}
sc.close();
}
}
public interface IWeek{
int MON=1, TUE=2, WED=3, THU=4, FRI=5, SAT=6, SUN=7;
}
enum(열거형)으로도 사용가능
/*
public class IWeek {
public final static int MON = 1;
public final static int TUE = 2;
public final static int WED = 3;
public final static int THU = 4;
public final static int FRI = 5;
public final static int SAT = 6;
public final static int SUN = 7;
}
*/
-ex
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
ROI: 9.15