-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
try 소괄호로 객체를 바로 생성하면 인터페이스 실행
23.09.01 00:14 작성 조회수 145
0
try(MyFileWriter writer2 = new MyFileWriter()){ writer2.write("빵이 먹고 싶어요."); } catch (Exception e){ e.printStackTrace(); }
이런 경우에 close()함수가 실행된다고 하셨는데요.
AutoCloseable이 아닌 인터페이스를 구현한 class인 경우에도,
try구문에 소괄호로 객체를 생성했을때 해당 인터페이스에 있는 메소드를 호출하나요?
답변을 작성해보세요.
0
나도코딩
지식공유자2023.09.02
안녕하세요?
try-with-resources는 자원을 관리하기 위해 AutoCloseable 인터페이스를 구현한 클래스에서만 작동합니다. 그렇기 때문에 AutoCloseable 인터페이스를 구현하지 않은 클래스는 try-with-resources 구문을 사용하여 자동으로 자원을 닫을 수 없습니다.
이해를 돕기 위해 다음과 같은 코드를 작성해봤어요.
먼저 close() 메소드를 포함한 인터페이스를 생성합니다.
public interface NotCloseable {
void close();
}
그런 다음에 NotCloseable 인터페이스를 구현하는 YourFileWriter 클래스를 만들어볼게요.
public class YourFileWriter implements NotCloseable {
@Override
public void close() {
System.out.println("파일을 과연 닫을까요?");
}
public void write(String line) {
System.out.println("파일에 내용을 입력합니다.");
System.out.println("입력 내용 : " + line);
}
}
마지막으로 테스트를 위한 코드를 작성합니다.
public class Sample {
public static void main(String[] args) {
try (YourFileWriter writer = new YourFileWriter()) {
writer.write("빵이 먹고 싶어요.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
그랬더니 아쉽게도 try-with-resources 구문에 다음과 같이 에러가 나타나네요.
AutoCloseable 를 구현하는 클래스가 아닌 YourFileWriter 는 사용할 수 없다고 하네요.
결과적으로 AutoCloseable 인터페이스를 구현하지 않는 클래스는 사용이 불가능합니다.
궁금증 해결에 도움되길 바라겠습니다 😊
감사합니다.
답변 1