17 [인강] 자바의정석 ch07
Machine translation — switch to KO for the original.
| 인터페이스의 다형성
class Figher extends Unit implements Fightable {
public void main (int x, int y) { }
public void attack (Fightable f) { }
}
매개변수의 타입이 인터페이스?
→ Fightable 인터페이스를 구현한 클래스의 인스턴스만 가능
interface Fightable {
void move (int x, int y);
void attack(Fightable f);
}
Fightable method () {
Figher f = new Fighter ();
return f; //return new Fighter();
}
인터페이스를 메서드의 리턴타입으로 지정할 수 있다
Fightable 인터페이스를 구현한 클래스의 인스턴스를 반환
| 인터페이스의 장점
두 객체 간 중간역할, 선언과 구현의 분리, 느슨한 결합, 유연한 코드
*GUI graphic user interface
변경의 최소화, 개발시간의 단축, 표준화가 가능(JDBC)
서로 관계없는 클래스들의 관계를 맺어줄 수 있다
interface Repairable { }
class SCV extends GroundUnit implements Repairable { ... }
...
| 디폴트메서드와 static 메서드
인터페이스에 디폴트메서드와 static 메서드를 JDK 1.8부터 추가
상속계층도
interface MyInterface {
void method();
default void newMethod() {}
}
디폴트 메서드가 기존의 메서드와 충돌할 때의 해결책
1. 여러 인터페이스의 디폴트 메서드 간의 충돌
- 구현 클래스에서 오버라이딩
2. 디폴트 메서드와 조상클래스의 메서드 간의 충돌
- 조상 클래스의 메서드가 상속, 디폴트는 무시됨
| 내부 클래스의 종류, 특징, 선언
클래스 안의 클래스
class A {
class B { }
}
내부 클래스에서 외부 클래스 멤버에 쉽게 접근 가능, 객체생성 없이도 가능
코드 복잡성 줄임, 캡슐화
class AAA {
int i = 100;
BBB b = new BBB();
class BBB {
void method () {
//AAA a = new AAA();
//System.out.println(a.i);
System.out.println(i);
}
}
}
인스턴스, 스태틱, 지역 내부 클래스 //변수특징과 동일
익명 내부 클래스: 일회용, 선언과 객체 생성을 동시에 하는 이름없는 클래스, 이벤트처리
| 내부 클래스의 제어자와 접근성
원래 클래스 앞에는 (default), public만 가능
내부 클래스는 접근제어자 4개 다 가능
static 클래스만 static 멤버를 정의할 수 있다.
→ 객체 생성없이 사용가능해야
final static은 상수이므로 허용
인스턴스 멤버에 직접 접근 불가, 외부 클래스를 먼저 생성해야 가능
내부클래스는 외부클래스의 private 멤버도 접근가능
값이 바뀌지 않는 변수는 상수로 간주함 → 내부클래스에서 접근가능, JDK 1.8부터 에러 아님
*constant pool
class Outer2 {
class InstanceInner {
int iv = 100;
}
static class StaticInner {
int iv = 200;
static int cv = 300;
}
}
Outer2.StaticInner si = new Outer2.StaticInner();
//외부클래스 이름을 붙여서 객체 생성해야
class Outer3 {
int value = 10;
class Inner {
int value = 20;
void method1() {
int value = 30;
System.out.println =("value:" +value);
System.out.println =("this.value:" +this.value);
System.out.println =("Outer3.this.value:" +Outer3.this.value);
| 익명 클래스
이름이 없는 일회용 클래스. 정의와 생성을 동시에
new 조상클래스이름 || 구현인터페이스이름 ( ) { }
AWT Java의 윈도우 프로그래밍
Comments
No comments yet. Be the first!
319 posts in 테크
- 368Supabase 프로젝트 복사하기 (Restore to a New Project)NEW
- 341Migrating from Permanent Access Tokens to Token Exchange — Why Order Matters
- 326Startup & Product Glossary: Terms Every Solo Founder Should Know
- 325Context Management — How I Do It Now
- 324Claude Code Routines vs Cowork Schedule — What's the Difference?