[์ดํŽ™ํ‹ฐ๋ธŒ ์ž๋ฐ”] Item02 ์™„๋ฒฝ๊ณต๋žต. ์ž๋ฐ”๋นˆ(JavaBean)

2023. 1. 6. 16:53ใ†JAVA/Effective JAVA

728x90

 

item02. ์ƒ์„ฑ์ž์— ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ๋งŽ๋‹ค๋ฉด ๋นŒ๋”๋ฅผ ๊ณ ๋ คํ•˜๋ผ. 

" p15. ์ž๋ฐ”๋นˆ์ฆˆ"

 

 

์ž๋ฐ”๋นˆ(Java Bean) ์ด๋ž€? 

"A Java Bean is a reusable software component that can be manipulated visually in a builder tool" 

Java Bean์€ ๋นŒ๋” ๋„๊ตฌ์—์„œ ์‹œ๊ฐ์ ์œผ๋กœ ์กฐ์ž‘ํ•  ์ˆ˜์žˆ๋Š” ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์†Œํ”„ํŠธ์›จ์–ด ๊ตฌ์„ฑ์š”์†Œ๋‹ค. 

-> (์ฃผ๋กœ GUI์—์„œ) ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์†Œํ”„ํŠธ์›จ์–ด ์ปดํฌ๋„ŒํŠธ 

 

 

์ž๋ฐ”๋นˆ(Java Bean) ์ด ์ง€์ผœ์•ผ ํ•˜๋Š” ๊ทœ์•ฝ 

- ์ž๋ฐ”๋นˆ์€ ์ธ์ž๊ฐ€ ์—†๋Š” ๊ธฐ๋ณธ ์ƒ์„ฑ์ž(default constructor)๋ฅผ ๊ฐ–๋Š”๋‹ค. 
- ํด๋ž˜์Šค์˜ ํ”„๋กœํผํ‹ฐ๋“ค์€ Getter/Setter ๋ฅผ ํ†ตํ•ด ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. 
- Serializable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•ด์•ผ ํ•œ๋‹ค. 

 

public class NutritionFacts implements Serializable
{
    private static final long serialVersionUID = 1L;
    private  int servingSize;  // (mL, 1 ํšŒ ์ œ๊ณต๋Ÿ‰)     ํ•„์ˆ˜
    private  int servings;     // (ํšŒ, ์ด nํšŒ ์ œ๊ณต๋Ÿ‰)    ํ•„์ˆ˜
    private  int calories;     // (1ํšŒ ์ œ๊ณตใ„ท๋Ÿ‰๋‹น)       ์„ ํƒ
    private  int fat;          // (g/1ํšŒ ์ œ๊ณต๋Ÿ‰))       ์„ ํƒ
    private  int sodium;       // (mg/1ํšŒ ์ œ๊ณต๋Ÿ‰)       ์„ ํƒ
    private  int carbohydrate; // (g/1ํšŒ ์ œ๊ณต๋Ÿ‰)        ์„ ํƒ

    public NutritionFacts() {
    }

    public void setServingSize(int servingSize) {
        this.servingSize = servingSize;
    }

    public void setServings(int servings) {
        this.servings = servings;
    }

    public void setCalories(int calories) {
        this.calories = calories;
    }

    public void setFat(int fat) {
        this.fat = fat;
    }

    public void setSodium(int sodium) {
        this.sodium = sodium;
    }

    public void setCarbohydrate(int carbohydrate) {
        this.carbohydrate = carbohydrate;
    }
    
    public int getServingSize()
    {
        return servingSize;
    }
    
    public int getServings()
    {
        return servings;
    }
    
    public int getCalories()
    {
        return calories;
    }
    
    public int getFat()
    {
        return fat;
    }
    
    public int getSodium()
    {
        return sodium;
    }
    
    public int getCarbohydrate()
    {
        return carbohydrate;
    }
}

 

๐Ÿ’Œ

์ด๋Ÿฌํ•œ ์ž๋ฐ”๋นˆ ์ŠคํŒฉ ์ค‘์—์„œ getter,setter๊ฐ€ ์ฃผ๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋Š”๋ฐ ๊ทธ ์ด์œ ๋Š”  JPA๋‚˜ ์Šคํ”„๋ง๊ณผ ๊ฐ™์€ ์—ฌ๋Ÿฌ ํ”„๋ ˆ์ž„์›Œํฌ์—์„œ ๋ฆฌํ”Œ๋ ‰์…˜์„ ํ†ตํ•ด ํŠน์ • ๊ฐ์ฒด์˜ ๊ฐ’์„ ์กฐํšŒํ•˜๊ฑฐ๋‚˜ ์„ค์ •ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90