๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[Java]์ž๋ฐ”์˜ ์ƒ์„ฑ์ž(Constructor)์™€ Getter/Setter ๋ณธ๋ฌธ

๐ŸชJava

[Java]์ž๋ฐ”์˜ ์ƒ์„ฑ์ž(Constructor)์™€ Getter/Setter

๋ฃจ๋ฆฌ์•ผใ…‘ 2023. 12. 20. 12:30
๋ฐ˜์‘ํ˜•

์ž๋ฐ”์—์„œ๋Š” ์ƒ์„ฑ์ž๋กœ ๊ณต๊ฐ„์„ ๋จผ์ € ํ˜•์„ฑํ•œ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ํ˜•์„ฑ๋œ ๊ณต๊ฐ„์— ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ๊ณ 
๋ณ€์ˆ˜๋กœ ๊ทธ ๊ณต๊ฐ„์„ ๊ฐ€๋ฆฌํ‚จ๋‹ค.

 

1. ํด๋ž˜์Šค ์ƒ์„ฑ

ํด๋ž˜์Šค ํ•˜๋‚˜๋ฅผ ์ƒ์„ฑํ•ด์„œ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•˜๊ณ  ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ ๋‹ค.

๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ถ”๊ฐ€ํ•œ ํ•จ์ˆ˜์™€, print ํ•จ์ˆ˜ 2๊ฐœ๋ฅผ ๋งŒ๋“ ๋‹ค.

public class Member {
    String name;
    String tel;
    String address;

    Member(){
        // ๋Œ์•„๊ฐ€๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด์„œ ๋งŒ๋“  ๊ธฐ๋ณธ ์ƒ์„ฑ์ž.
    }

    Member(String name, String tel, String address){
        this.name = name;
        this.tel = tel;
        this.address = address;
    }
    
    void print(){
        System.out.println(name + " " + tel + " " + address);
    }
}

 

 

2. ๋ฉ”์ธ ํด๋ž˜์Šค ์ƒ์„ฑ

์ƒ์„ฑ์ž๋กœ ๊ณต๊ฐ„์„ ์ƒ์„ฑํ•˜๊ณ  ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์–ด์„œ ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ์‹๊ณผ
๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋„ฃ์–ด ์ถœ๋ ฅํ•˜๋Š” ๋ฐฉ์‹, 2๊ฐ€์ง€๋กœ ์ถœ๋ ฅ์„ ํ•ด๋ณธ๋‹ค.

public class MemberTest {

    public static void main(String[] args) {
        Member m1 = new Member(); // 1. ๊ณต๊ฐ„์ƒ์„ฑ

        m1.name = "ํ™๊ธธ๋™";
        m1.tel = "010-1111-2222";
        m1.address = "์ธ์ฒœ์‹œ ์„œ๊ตฌ ๊ฐ€์ •๋™";

        Member m2 = new Member("๋ˆ„๊ตฌ","010-1234-5467","์–ด๋”˜๊ฐ€ ์‚ด์–ด์š”");

        m1.print();
        m2.print();

    }

}

 

3. getter/setter

๋จผ์ € Member ํด๋ž˜์Šค์—์„œ get/set  ํ•จ์ˆ˜๋ฅผ ์„ธํŒ…ํ•œ๋‹ค.

getter๋Š” return์ด ์žˆ๊ณ 
setter๋Š” return์ด ์—†์–ด์„œ void๋ฅผ ์ž…๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

public class Member {
    String name;
    String tel;
    String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

 

๋ฉ”์ธ ํด๋ž˜์Šค์—์„œ๋Š”

์ƒ์„ฑ์ž๋ฅผ ๋งŒ๋“ค์–ด ๋ณ€์ˆ˜์— ๋„ฃ์–ด์ฃผ๊ณ 
set์˜ ๊ฐ’์„ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๋„ฃ๋Š”๋‹ค.

๊ทธ๋ฆฌ๊ณ  ์•„๋ž˜ get์œผ๋กœ ๊ทธ ๊ฐ’์„ ํ”„๋ฆฐํŠธ ํ•ด๋ณธ๋‹ค.

public class MemberTest {

    public static void main(String[] args) {

        Member m4 = new Member();
        //setter
        m4.setName("์ฒ ์ˆ˜");
        m4.setTel("010-1111-1111");
        m4.setAddress("์ธ์ฒœ ์„œ๊ตฌ");

        //getter
        m4.getName();
        
        System.out.println(m4.getName());
    }

}

๊ทธ๋Ÿผ set์œผ๋กœ ๋งŒ๋“ค์—ˆ๋˜ ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.

๋ฐ˜์‘ํ˜•