interface is class with abstract methods and constant
Calc.java
package interfaceex;
public interface Calc {
double PI=3.14;
int ERROR=-999999999;
int add(int num1, int num2);
int sbustract(int num1, int num2);
int times(int num1, int num2);
int divide(int num1, int num2);
default void description(){
System.out.println("정수 계산기를 구현합니다.");
}
static int tatal(int[] arr){
int total=0;
for(int i:arr){
total+=i;
}
myStaticMethod();
return total;
}
private void myMethod(){
System.out.println("private 메소드입니다.");
}
}
when in interface variables transform to constant,
and methods transform to abstract method when compiling
ex) double PI=3.14;
-> public static final double PI=3.14;
implements
implements is key word for use interface at the other class
Calculator.java
package interfaceex;
public abstract class Calculator implements Calc{
@Override
public int add(int num1, int num2) {
return num1+num2;
}
@Override
public int sbustract(int num1, int num2) {
return num1-num2;
}
}
CompleteCalc.java
package interfaceex;
public class CompleteCalc extends Calculator{
@Override
public int times(int num1, int num2) {
return num1*num2;
}
@Override
public int divide(int num1, int num2) {
if(num2!=0)return num1/num2;
else return Calc.ERROR;
}
public void show Info() {
System.out.println("Calc 인터페이스를 구현하였습니다.");
}
}
default method
default keyword is use for declare method in interface
static method
static method can use regardless instance
private method
private clarfied method only be used in interface
추상 클래스는 단일 상속만 가능하며,
인터페이스 클래스는 다중 구현이 가능하다.
package interfaceex;
public class implements Buy,Sell{
}
클래스가 클래스를 상속받을 때는 extends 예약어 사용
인터페이스가 인터페이스를 구현받을 때는 extends 예약어를 사용
클래스가 인터페이스를 구현받을 때 implements 예약어 사용
extends & implements
Shelf.java
package bookshelf;
import java.util.ArrayList;
public class Shelf {
protected ArrayList<String> shelf;
public Shelf() {
shelf=new ArrayList<String>();
}
public ArrayList<String> getShelf(){
return shelf;
}
public int getCount() {
return shelf.size();
}
}
Queue.java
package bookshelf;
public interface Queue {
void enQueue(String title);
String deQueue();
int getSize();
}
BookShelf.java
package bookshelf;
public class BookShelf extends Shelf implements Queue{
@Override
public void enQueue(String title) {
shelf.add(title);
}
@Override
public String deQueue() {
return shelf.remove(0);
}
@Override
public int getSize() {
return getCount();
}
}
BookShelfTest.java
package bookshelf;
public class BookShelfTest {
public static void main(String[] args) {
Queue shelfQueue=new BookShelf();
shelfQueue.enQueue("태백산맥 1");
shelfQueue.enQueue("태백산맥 2");
shelfQueue.enQueue("태백산맥 3");
System.out.println(shelfQueue.deQueue());
System.out.println(shelfQueue.deQueue());
System.out.println(shelfQueue.deQueue());
}
}
Marker interface
마커 인터페이스는 Cloneable 인터페이스와 같이 선언해도 별도로 구현해야하는 메서드가 없는
인터페이스를 말한다.