티스토리 뷰
💡 해당 클래스의 인스턴스 생성 시 어떤 생성자를 활용해서 인스턴스를 생성하더라도 공통적으로 실행 될 코드를 작성할 수 있는 블럭이다.
- 인스턴스 변수
- 클래스 변수
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 +
'}';
}
}
'한화시스템 > 백엔드' 카테고리의 다른 글
[BE] JAVA_클래스와 객체_uses 예제 (0) | 2024.07.16 |
---|---|
[BE] JAVA_클래스와 객체_객체 배열 (0) | 2024.07.16 |
[BE] JAVA_클래스와 객체_Singleton & StaticKeyword (0) | 2024.07.16 |
[BE] JAVA_클래스와 객체_오버로딩 & 매개변수 (0) | 2024.07.16 |
[BE] JAVA_클래스와 객체_생성자 (0) | 2024.07.16 |