본문 바로가기
Backend/JAVA_Basic

21. JAVA, 추상화 (추상 클래스, 추상 메소드, 인터페이스, 익명내부객체)

by 개발개발빈이 2022. 6. 5.

Pablo Picasso, The Bull (1946) : 꼭 필요한 선만 남긴 황소 그림처럼 프로그래밍에서도 꼭 필요한 것만 남기는 추상화가 존재한다

 

○  추상화 (Abstraction)

    - 객체지향 프로그래밍의 특징 중 하나 (참고 : OOP의 특징)

    - 불필요한 정보의 노출을 최소화하고 꼭 필요한 정보만 노출하는 것

    - 캡슐화(encapsulation), 정보은닉(information hiding)과 관련

 

○  추상 메소드 (Abstract method)

    - 미완성 메소드 : 메소드의 body {}가 없는 함수
    - 메소드를 선언만 해 놓음
    - 형식) abstract 리턴형 함수명 ();

void view() {}         //일반메소드
abstract void disp();  //추상메소드(미완성)

 

○  추상 클래스 (Abstract class)

    - 미완성 클래스 : 추상 메소드가 1개라도 있으면 추상 클래스
    - 일반 메소드와 추상 메소드를 같이 선언 가능
    - 객체를 생성할 수 없음 (new연산자를 직접 사용할 수 없음)

    - 추상클래스는 주로 부모역할만 함

      추상클래스를 상속받은 자식클래스는 반드시 추상메소드를 완성해햐 함(override)

abstract class Animal {//추상클래스
	String name;
	void view() {}        //일반메소드
	abstract void disp(); //추상메소드(미완성)
}


class Elephant extends Animal {
	@Override		
	void disp() {
		System.out.println("점보");
	}
}


public class Test04_abstract {

    public static void main(String[] args) {
    
    	//Animal ani = new Animal();  에러, 추상클래스는 new연산자로 객체 생성 불가
    
    	Elephant jumbo = new Elephant();
        jumbo.disp();
		
    }//main() end

}//class end

 

○  인터페이스 (Interface)

    - 추상메소드만 선언 가능

    - 추상클래스보다 더 추상화 되어 있음

    - 인터페이스는 직접 객체 생성 불가능

    - 인터페이스를 상속할 때는 implements(구현)

interface Creature {
	
	//void disp() {} 에러, 일반 메소드는 사용 불가
	
	abstract void kind();  //추상 메소드만 가능하다
	void breathe();        //abstract 생략가능 (interface내에서는)
		
}//interface end


class Tiger implements Creature {//부모가 인터페이스 : implements 구현

	@Override
	public void kind() {
		System.out.println("포유류");
	}

	@Override
	public void breathe() {
		System.out.println("허파");	
	}
		
}//class end


public class Test06_interface {

    public static void main(String[] args) {
                
        // Creature ct = new Creature(); 에러, 인터페이스는 직접 객체 생성 불가능
    	
        Creature creature = new Tiger(); //인터페이스에서의 다형성
        creature.kind();
        creature.breathe();
    
    }//main() end

}//class end

 

○ 클래스와  인터페이스의 상속

    - 클래스는 단일상속만 가능하지만 인터페이스는 다중상속이 가능함

class Unit{
	int currentHP;
	int x, y;	
}//class end


interface Movable {
	void move(int x, int y);
}//interface end


interface Attckable {
	void attack(Unit u);
}//interface end

interface Fightable extends Movable, Attckable { 
	// 인터페이스 간의 상속은 다중상속이 가능하다
}//interface end


class Fight extends Unit  //클래스는 단일상속만 가능하다
			implements Fightable {	//클래스 1개와 인터페이스 1개 이상 동시 상속 가능

	@Override
	public void move(int x, int y) { }

	@Override
	public void attack(Unit u) {}

}//class end


class Tetris extends Unit implements Movable, Attckable {
	//클래스는 단일상속만 가능하고, 인터페이스는 다중구현이 가능
	
	@Override
	public void move(int x, int y) {}

	@Override
	public void attack(Unit u) {}
	
}//class end

 

○  익명 내부 객체 (Anonymous class)

    - 인터페이스는 추상메소드 때문에 직접 객체 생성이 불가능

    - 인터페이스를 객체 생성 하고 싶다면

          ①인터페이스를 상속받아 추상메소드를 오버라이드 하거나,

          ② 다형성을 이용하거나,

          ③ 익명객체를 이용하는 방법이 있음

    - 익명객체 : 필요한 곳에서 일시적으로 생성, 이벤트(JavaScript)가 발생할 때만 실행

                        (→ 모바일 앱, Java Script, jQuery등에서 많이 사용)

                        예) $("button").click() {}

interface IMessage {
	public void msgPrint();  //추상메소드	
}//interface end


class Message implements IMessage {
	@Override
	public void msgPrint() {
		System.out.println("Message 클래스");		
	}		
}//class end


public class Test09_anonymous {

    public static void main(String[] args) {

        //IMessage msg = new IMessage(); 에러, 인터페이스 직접 객체 생성 불가
        
        Message msg = new Message();    //1) 오버라이드
        msg.msgPrint();
        
        IMessage imess = new Message(); //2) 다형성 이용
        imess.msgPrint();
        
        
        IMessage mess = new IMessage() {//3) 익명객체 이용
            @Override
            public void msgPrint() {
                System.out.println("익명 내부 객체");
            }
        };


	}//main() end

}//class end

댓글