-
백기선님의 Java 스터디를 진행하며 찾아본 내용입니다.
https://limkydev.tistory.com/197?category=957527
[JAVA] 자바 인터페이스란?(Interface)_이 글 하나로 박살내자
1. 인터페이스 개념과 역할 인터페이스....이 글하나로 박살내자. (회사에서 존댓말을 많이 쓰기때문에 여기서라도 반말로 글을 써보고 싶음 ㅎ) 인터페이스는 뭘까?? 결론부터 말하면, 극단적으
limkydev.tistory.com
위의 블로그를 많이 참고했습니다.
목표
자바의 인터페이스에 대해 학습하세요.
학습할 것
- 인터페이스 정의하는 방법
- 인터페이스 구현하는 방법
- 인터페이스 레퍼런스를 통해 구현체를 사용하는 방법
- 인터페이스 상속
- 인터페이스의 기본 메소드 (Default Method), 자바 8
- 인터페이스의 static 메소드, 자바 8
- 인터페이스의 private 메소드, 자바 9
인터페이스 정의하는 방법
인터페이스란?
- 극단적으로 동일한 목적 하에 동일한 기능을 수행하게끔 강제하는 것이 인터페이스의 역할이자 개념이다.
- 자바의 다형성을 극대화하여 개발코드 수정을 줄이고 프로그램 유지 보수성을 높이기 위해 인터페이스를 사용한다.
- 코드를 개발시 일종의 '가이드 라인'을 제공해준다고 볼 수 있다.
- 대학교 과제를 제출해야 할 때 .PPTX파일로 제출해야하고, 15Page 이내로 작성해야 한다고 가이드라인을 제공해주는 것과 비슷하다고 생각하면 된다.
- 인터페이스를 이용하면 상속한 클래스들의 공통 규격을 제공 할 수 있어 호환성이 높아지고 유지보수성이 증가된다.
인터페이스 정의
인터페이스는 interface 키워드, 인터페이스 이름, ','로 구분할 수 있는 부모 인터페이스들, 인터페이스 body로 구성된다.
인터페이스는 인스턴스화 되어질 수 없다.
인터페이스 내의 메소드는 추상메소드, 상수, default method나 static method, private method 만이 존재 할 수 있다
from - https://limkydev.tistory.com/197?category=957527 각각은 다음과 같은 의미를 가지고 있다.
- 상수 : 인터페이스에서 값을 정해줄테니 함부로 바꾸지 말고 제공해주는 값만 참조해라 (절대적)
- 추상메소드 : 가이드만 줄테니 추상 메소드를 오버라이딩해서 재구현해라 (강제적)
- 디폴트메소드 : 인터페이스에서 기본적으로 제공해주지만, 마음에 안들면 각자 구현해서 써라. (선택적)
- 정적메소드 : 인터페이스에서 제공해주는 것으로 무조건 사용해라 (절대적)
인터페이스 구현하는 방법
- 인터페이스를 구현하기 위해선 implements 키워드를 클래스 선언에 포함해야 한다.
- 하나 이상의 인터페이스를 구현 할 수 있다.
- 관례적으로 implements절은 extends절의 뒤쪽에 위치한다.
12345678910111213141516171819interface In1 {final int a = 10;void display();}class TestClass implements In1 {public void display() {System.out.println("TestClass");}public static void main(String[] args) {TestClass t = new TestClass();t.display();;System.out.println(a);}}cs
인터페이스 레퍼런스를 통해 구현체를 사용하는 방법
인터페이스를 다형성을 이용해 구현 할 수 있다.
다음과 같이 인터페이스를 사용 할 수 있다.
123public interface Game {void name();}cs 1234567891011public class HollowKnight implements Game{@Overridepublic void name() {System.out.println("할로우 나이트");}public void genre() {System.out.println("플랫포머류 게임");}}cs 1234567891011public class OxygenNotIncluded implements Game{@Overridepublic void name() {System.out.println("산소미포함");}public void publisher_name() {System.out.println("Klei");}}cs 1234567891011121314public class Main {public static void main(String[] args) {Game hollow_knight = new HollowKnight();Game oxygen_not_included = new OxygenNotIncluded();hollow_knight.name();oxygen_not_included.name();// hollow_knight.genre() 사용불가// oxygen_not_included.publisher_name() 사용불가((HollowKnight)hollow_knight).genre(); // 캐스팅 후 사용 가능((OxygenNotIncluded)oxygen_not_included).publisher_name(); // 캐스팅 후 사용 가능}}cs
인터페이스 상속
인터페이스는 클래스와 다르게 다중 상속이 가능하다
인터페이스의 기본 메소드 (Default Method), 자바 8
디폴트 메소드는 JAVA 8 부터 도입된 기능으로써, 인터페이스에 body를 가진(구현을 하는) 메소드를 제공한다
1234567891011121314151617181920212223242526interface TestInterface {// abstract classpublic void square(int a);// default classdefault void show() {System.out.println("Default Method Executed");}}public class TestClass implements TestInterface{// implementation of square abstract method@Overridepublic void square(int a) {System.out.println(a*a);}public static void main(String args[]) {TestClass d = new TestClass();d.square(4);// default method executedd.show();}}cs
인터페이스의 static 메소드
인터페이스 내에서 구현까지되어있는 메소드이다. 정적인 메소드이므로 Overriden이나 구현된 클래스에서의 변경을 금한다.
123456789101112131415161718192021222324252627interface NewInterface {// static methodstatic void hello() {System.out.println("Hello, New Static Method Here");}// public and abstract method of Interfacevoid override_method(String str);}public class InterfaceDemo implements NewInterface{public static void main(String[] args) {InterfaceDemo interfaceDemo = new InterfaceDemo();// Calling the static method of interfaceNewInterface.hello();// Calling the abstract method of interfaceinterfaceDemo.override_method("Hello, Override Method here");}@Overridepublic void override_method(String str) {System.out.println(str);}}cs Output:
인터페이스의 private 메소드, 자바 9
JAVA 9에 들어오면서 인터페이스는 다음 6개의 요소를 가질 수 있게 되었다.
- Constant Variable
- Abstract Method
- Default Method
- Static Method
- Private Method
- Private Static Method
이 중에서 Private Method는 인터페이스 내에서만 사용되어 질 수 있는 메소드로써 다른 인터페이스나 클래스에 접근되거나 상속시킬 수 없다.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455// Java 9 program to illustrate// private methods in interfacespublic interface TempI {public abstract void mul(int a, int b);public default voidadd(int a, int b){// private method inside default methodsub(a, b);// static method inside other non-static methoddiv(a, b);System.out.print("Answer by Default method = ");System.out.println(a + b);}public static void mod(int a, int b){div(a, b); // static method inside other static methodSystem.out.print("Answer by Static method = ");System.out.println(a % b);}private void sub(int a, int b){System.out.print("Answer by Private method = ");System.out.println(a - b);}private static void div(int a, int b){System.out.print("Answer by Private static method = ");System.out.println(a / b);}}class Temp implements TempI {@Overridepublic void mul(int a, int b){System.out.print("Answer by Abstract method = ");System.out.println(a * b);}public static void main(String[] args){TempI in = new Temp();in.mul(2, 3);in.add(6, 2);TempI.mod(5, 3);}}cs Output:
인터페이스에서 Private 메소드를 사용할 때 유의사항
- Private 인터페이스 메소드는 abstract로 사용 할 수 없다.
- Private 메소드는 인터페이스 내의 다른 메소드에서만 사용 할 수 있다.
- static이 아닌 Private 메소드는 private static 메소드 내에서 사용 할 수 없다.
References
https://limkydev.tistory.com/197?category=957527
[JAVA] 자바 인터페이스란?(Interface)_이 글 하나로 박살내자
1. 인터페이스 개념과 역할 인터페이스....이 글하나로 박살내자. (회사에서 존댓말을 많이 쓰기때문에 여기서라도 반말로 글을 써보고 싶음 ㅎ) 인터페이스는 뭘까?? 결론부터 말하면, 극단적으
limkydev.tistory.com
docs.oracle.com/javase/tutorial/java/concepts/interface.html
What Is an Interface? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Conc
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated
docs.oracle.com
docs.oracle.com/javase/tutorial/java/IandI/interfaceDef.html
Defining an Interface (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated
docs.oracle.com
docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
Implementing an Interface (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated
docs.oracle.com
docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
Default Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated
docs.oracle.com
www.geeksforgeeks.org/default-methods-java/
Default Methods In Java 8 - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
www.geeksforgeeks.org/static-method-in-interface-in-java/
Static method in Interface in Java - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
www.geeksforgeeks.org/private-methods-java-9-interfaces/
Private Methods in Java 9 Interfaces - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
leegicheol.github.io/whiteship-live-study/whiteship-live-study-08-interface/
WhiteShip Live Study 8주차. 인터페이스
WhiteShip Live Study 8주차. 인터페이스
leegicheol.github.io