Java 프로그래밍 기초 9 - 인터페이스와 추상 클래스

2020. 3. 13. 17:42Study/Computer Science

1. 인터페이스

클래스에서 구현해야하는 작업 명세서, 인터페이스에서 나온 메서드들을 implement한 클래스에서 반드시 구현해야함.

인터페이스를 사용하는 가장 큰 이유는 객체가 다양한 자료형(타입) 을 가질 수 있기 때문이다.

 

//인터페이스
interface Calculatable{
	public void setOprands(int first, int second);
	public int sum();
	public int avg();
}


//인터페이스를 구현하는 Calculate 클래스
class Calculate implements Calculatable{ //Calculatable 인터페이스를 Calculate 클래스가 implements 한다
	int first, second;
	public void setOprands(int first, int second) {
		this.first = first;
		this.second = second;
	}
	public int sum() {
		return this.first + this.second;
	};
	public int avg() {
		return (this.first + this.second)/2;
	};
	
}

class CalculatorConsumer {
    public static void main(String[] args) {
        Calculate c = new Calculate();
        c.setOprands(10, 20);
        System.out.println(c.sum() + "," + c.avg());
    }
}

규칙

-   하나의 클래스가 여러개의 인터페이스를 구현(implements) 할 수 있다

    (class A implements I1, I2 이런 형식)

 

-   인터페이스도 상속이 된다

     ( interface I1{};

       interface I2 extends I1{} 형식)

 

-   인터페이스의 멤버는 반드시 public이다. (외부에서 접근 자유로워야 되므로)

 

2. 추상 클래스

구체적이지 않은 클래스, 여러 클래스에서 공통적으로 사용하는 메서드들을 정의한 것. 추상 메서드 뿐 아니라 일반 메서드도 가질 수 있으며, 일반 클래스와 마찬가지로 생성자도 있음.

 

<사용법>

 

-   class 키워드 앞에 abstract 키워드 추가해서 정의

 

-   추상 클래스는 미완성의 추상 메서드 (구현이 되지 않은 메서드) 포함 가능

     마찬가지로 추상 메서드 리턴형 앞에 absract 키워드 사용

 

-   추상 클래스는 인스턴스 생성 불가

 

-   추상 클래스를 상속받은 클래스는 추상 메서드를 반드시 구현해야 함.

    추상 클래스를 상속받고 구현하지 않을 시 해당 클래스 추상클래스로 해야됨.

 

<Abstracttest.java>

package package1;

public class Abstracttest {
	public static void main(String[] args) {
		Dog Ban = new Dog();
		Ban.sing();
		Ban.run();
        // Animal a = new Animal() 은 불가능, 추상클래스는 인스턴스 생성 불가
	}
}

<Animal.java>

package package1;

public abstract class Animal {
	public abstract void sing();
	
	public void run() {
		System.out.println("달리다");
	}
}

<Dog.java>

package package1;

public class Dog extends Animal {
	@Override   //상속받은 추상메서드 구현, 하지 않을 시 Dog 클래스도 추상 클래스가 됨
	public void sing(){
		System.out.println("멍멍");
	}
}

 

인터페이스 VS 추상 클래스