티스토리 뷰

💡 해당 클래스의 인스턴스 생성 시 어떤 생성자를 활용해서 인스턴스를 생성하더라도 공통적으로 실행 될 코드를 작성할 수 있는 블럭이다.
  • 인스턴스 변수

  • 클래스 변수

 

package com.ohgiraffers.section07.initblock;

public class Application {
    public static void main(String[] args) {
        Product product = new Product();        // 순서대로 나오는지 확인
        System.out.println(product);

    }
}

// 실행 결과
초기화 블럭 실행...
Product 기본생성자 호출됨...
Product{name='아이뽕', price=0, brand=헬쥐}
package com.ohgiraffers.section07.initblock;

public class Product {
    private String name = "아이폰";            // 상품명
    private int price;              // 상품가격
    private static String brand;    // 제조자
    // final은 접근제어자와 반환타입 사이에! static과 순서는 바뀌어도 무관!

    {
        System.out.println("초기화 블럭 실행...");
        name = "헬쥐폰";
        brand = "헬쥐";       // final로 변경 시 왜 에러??? static이 우선순위가 있어 먼저 바뀌고
                             // 나중에 바뀌려고 하는데 final이라 바뀌지 않는다.
    }

    static {    // static이 우선순위가 더 높다.
//        name = "싸이온";
        brand = "엘지";       // final일 때 초기화? static이 우선순위 높아서...
    }

    public Product() {
        System.out.println("Product 기본생성자 호출됨...");
        name = "아이뽕";
    }

    @Override
    public String toString() {
        return "Product{" +
                "name='" + this.name + '\'' +           // this. 및 Product. 생략 가능
                ", price=" + this.price +
                ", brand=" + Product.brand +
                '}';
    }
}

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함