인터페이스란?
인터페이스란 추상클래스보다 추상적인 클래스라고 생각할 수 있다.
인터페이스는 오직 클래스 메서드와 클래스 변수만 가질 수 있다. 따라서 전부 미완성인 메서드들로만 구성되어 있습니다.
인터페이스 사용법
기본 사용법
interface InterfaceClass {
/**
* 모든 인터페이스의 변수는 public static final이 기본이다.
*/
public static final int VALUE1 = 5;
public final int VALUE2 = 5;
public static int VALUE3 = 5;
public int VALUE4 = 5;
int VALUE5 = 5;
/**
* 인터페이스 메소드는 public abstract가 기본이다.
*/
public abstract void method();
public void method(int a);
void method(String s);
/**
* JDK 1.8이상 부터 default메서드와 static 메서드가 가능해졌다.
*/
default void defaultMethod() {}
}
위와 같이 생략되는 접근 제어자는 컴파일시 자동 생성한다.
인터페이스 상속 사용법
interface InterfaceClass {
int VALUE = 5;
void method(int a);
}
interface InterfaceClass2 {
int VALUE = 10;
void method(int a);
}
interface InterfaceClass3 {
int THREE = 3;
void last();
}
interface MotherInterface extends InterfaceClass2, InterfaceClass{}
class ImplInterface implements InterfaceClass, InterfaceClass2 {
@Override
public void method(int a) {}
}
abstract class ImplInterface2 extends ImplInterface implements InterfaceClass3 {}
class LastClass extends ImplInterface2 {
@Override
public void last() {
}
}
기능
- 인터페이스는 클래스와 달리 다중 상속이 가능하다.
- 추상클래스와 동일하듯 상속 받은 클래스가 추상 메서드를 구현하지 않은 경우 똑같이 추상 클래스를 붙여야 한다.
- 클래스와 인터페이스를 동일하게 상속 받을 수 있다.
- 인터페이스는 인터페이스를 상속받을 때 extends 를 사용하여 받는다.
다중 상속
인터페이스에서는 모든 메서드가 static이다 따라서 상속받는 클래스에서 override만 하면 되므로 문제가 되지 않는다.
만약 클래스에서 상속이 진행될 경우
- 두 클래스 중 비중이 높은 쪽은 놔두고 다른 쪽을 멤버 변수로 클래스를 넣는다.
- 필요한 부분을 봅아 인터페이스로 만들고 구현
상속을 통한 장점으로는 다형성이 있는데 다중 상속을 하지 않고 멤버 변수로 했을 경우도 사용이 가능합니다. 하지만 이렇게 하는 경우 다형성의 특성을 이용하지 못하게 된다 따라서 다중 상속에서의 장점인 여러 다형성을 통해 단순화를 얻기 위해서 인터페이스로 분리한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 |
class Main {
public static void main(String[] args) {
Computer computer = new Computer();
System.out.println(computer instanceof IMonitor);
}
}
interface IMonitor {
void setArm();
}
class Monitor {
void setArm(){}
}
interface IKeyboard {
void keyBoardType();
}
class Keyboard {
void keyBoardType(){}
}
class ComputerBody {
}
class Computer extends ComputerBody implements IMonitor, IKeyboard{
Monitor monitor = new Monitor();
Keyboard keyboard = new Keyboard();
@Override
public void setArm() {
}
@Override
public void keyBoardType() {
}
}
|
위와 같이 기능이 추가될 때마다 인터페이스에 새로운 메서드를 추가해야한다 하지만 이렇게 한다면 다형성을 추가할 수 있다.
인터페이스 장점
1. 개발 시간의 단축
인터페이스를 통해 메서드를 호출하는 쪽에서는 어떤 결과를 받는지 알 수 있습니다. 따라서 선언부만 알아도 해당 메서드가 구현이 완료되지 않아도 사용할 수 있어서 양쪽에서 동시에 구현이 가능하다
2. 표준화 가능
위 개발 단축의 이유와 비슷하다. 선언부만 알아도 개발이 가능하기 때문에 구조적인 개발이 가능하다.
3. 클래스간 관계성 추가
서로 상관관계에 없다면 상속의 특징인 다형성을 통해 묶을 수 없지만 인터페이스를 통해 서로 관계를 맺을 수 있다.
4. 독립적 프로그래밍
결국 1번의 이유와 같다. 또한 각 클래스간 영향력이 줄어든다.
Default 메서드 & Static 메서드 (자바8이상) & Private 메서드 (자바9이상)
인터페이스에서는 지금까지 추상 클래스에 대해서만 제공했습니다.
하지만 이제 인터페이스에서 기본적으로 제공하는 함수는 default Method를 제공합니다. 즉 함수의 내용을 담고 있는데 이렇게 되면 다중 상속의 문제점인 충돌이 생기게 된다.
private 메서드 : interface 내부에서만 사용하는 메서드
- static private 메서드 : interface 내부 static메서드에서만 사용 가능
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
class Main {
public static void main(String[] args) {
Child c = new Child();
c.method();
c.defaultMethod();
c.defaultMethod2();
Parent p = new Child();
p.method();
p.defaultMethod();
// p.defaultMethod2();
ParentInterface.staticMethod();
ChildInterface.staticMethod();
}
}
interface ParentInterface {
default void defaultMethod() {
System.out.println("ParentInterface");
}
static void staticMethod() {
System.out.println("Parent Static Method");
}
}
interface ChildInterface extends ParentInterface {
default void defaultMethod() {
System.out.println("ChildInterface");
privateMethod();
}
default void defaultMethod2() {
System.out.println("ChildInterface2");
}
static void staticMethod() {
System.out.println("Child Static Method");
System.out.println("Private static Method");
}
private void privateMethod() {
System.out.println("Private Method");
}
private static void privateStaticMethod() {
System.out.println("Private static Method");
}
}
interface Interface2 {
default void defaultMethod2() {
System.out.println("interface2");
}
}
class Parent {
public void defaultMethod() {
System.out.println("Parent default method");
}
public void method() {
System.out.println("Parent method");
}
}
class Child extends Parent implements ChildInterface, Interface2{
public void method() {
System.out.println("Child method");
}
@Override
public void defaultMethod2() {
ChildInterface.super.defaultMethod2();
Interface2.super.defaultMethod2();
}
}
|
충돌 총 정리
부모 클래스 vs 자식 클래스
- 멤버 변수 : 참조 변수에 맞춰 간다
- 메소드 : 자식 클래스 ( 4 line vs 8 line )
부모 클래스 vs 인터페이스
- 부모 클래스의 메서드를 따라간다 ( 5 line vs 9 line )
서로 다른 인터페이스
- 새로 Override해야한다.
- 또한 인터페이스에 대해 직접 접근 가능 ( 6 line )
인터페이스간 상속
- 부모 클래스 vs 자식 클래스와 같다
'JAVA > 자바스터디' 카테고리의 다른 글
[자바스터디] Collection - List (0) | 2023.01.21 |
---|---|
예외 처리 (0) | 2022.11.19 |
상속 - 추상클래스 (0) | 2022.11.17 |
상속 - 다형성 (0) | 2022.11.17 |
JAVA - 제어자 (0) | 2022.11.14 |