익명 내부 클래스(anonymous inner class)는 이름을 갖지 않는 클래스다. 클래스 선언과 오브젝트 생성이 결합된 형태로 만들어 지며, 상속할 클래스나 구현할 인터페이스를 생성자 대신 사용해서 다음과 같은 형태로 만들어 사용한다. 클래스를 재사용할 필요가 없고, 구현한 인터페이스 타입으로만 사용할 경우에 유용하다.

  • new 인터페이스이름( ){ 클래스 본문 }

구체적인 예를 들어보자.

class DeleteAllStatement implements StatementStrategy{
       PreparedStatement makePreparedStatement(Connection c) throws SQLException{
           return c.prepareStatement("delete from users");
       }
}

StatementStrategy strategy = new TestStatementStategyDeleteAllStatement ();

strategy .makePreparedStatement(c)


위 같이 interface를 구현한 클래스를 하나 만들고  new로 인스턴스를 만들어 함수를 호출 하도록 하지만 이부분을 생략하고 아래 처럼 익명내부 클래스로 바로 사용할수도 있다. 그럼 interface를 구현한 클래스를 매번 만들 수고를 들수있다.

 

 

'JAVA' 카테고리의 다른 글

가변인자  (0) 2020.01.04

+ Recent posts