Programming/Java

[Java] ์ดˆ๊ธฐํ™”์™€ ์ƒ์„ฑ์ž

yuri lee 2022. 10. 24. 20:52
๋ฐ˜์‘ํ˜•
์ด ๊ธ€์€ ์ƒํ™œ์ฝ”๋”ฉ์˜ 'Java' ๊ฐ•์ขŒ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.

 

์ดˆ๊ธฐํ™”

์–ด๋–ค ์ผ์„ ์‹œ์ž‘ํ•˜๊ธฐ ์ „์— ์ค€๋น„ํ•˜๊ฒŒ ๋˜๋Š”๋ฐ, ์ด๋ฅผ ์ดˆ๊ธฐํ™”๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ์ฒด ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ๋„ ์ดˆ๊ธฐํ™”์— ํ•ด๋‹นํ•˜๋Š” ๊ธฐ๋Šฅ์ด ์ œ๊ณต๋˜๋Š”๋ฐ ์ด๋ฅผ ์ƒ์„ฑ์ž (constructor)๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค.  ์•ž์„œ ์‚ดํŽด๋ดค๋˜ ๊ณ„์‚ฐ๊ธฐ ์˜ˆ์ œ๋ฅผ ๋‹ค์‹œ ๋ด…์‹œ๋‹ค. 

Calculator c1 = new Calculator();
c1.setOprands(10, 20);
c1.sum();       
c1.avg();

 

๋ฉ”์†Œ๋“œ setOperands์˜ ๊ฐ’์œผ๋กœ 10๊ณผ 20์„ ์ง€์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด๋Š” ๊ฐ์ฒด ๋‚ด๋ถ€์—์„œ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜ left๊ณผ right์˜ ๊ฐ’์œผ๋กœ ์„ค์ •๋˜์–ด ์œ ์ง€๋ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฉ”์†Œ๋“œ setOperands ํ˜ธ์ถœํ•˜๊ธฐ ์ „์— sum๊ณผ avg๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค๋ฉด ์›ํ•˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. 

Calculator c1 = new Calculator();
c1.sum();       
c1.avg();

์ด๋Ÿฌํ•œ ์ ˆ์ฐจ๋ฅผ ๊ธฐ์–ตํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์€ ์‚ฌ์šฉ์ž ์ž…์žฅ์—์„œ ๋ถˆํŽธํ•  ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ์ž˜๋ชป๋œ ์‚ฌ์šฉ์œผ๋กœ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒ๋  ํ™•๋ฅ ์ด ๋†’์•„์ง‘๋‹ˆ๋‹ค. 

 

์ƒ์„ฑ์ž

๊ทธ๋ž˜์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๋ฐ”๋กœ ์ƒ์„ฑ์ž(Constructor)์ž…๋‹ˆ๋‹ค. ์•„๋ž˜์™€ ๊ฐ™์ด ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ ์‹œ left, right ๊ฐ’์„ ์ž…๋ ฅํ•˜๋„๋ก ๊ฐ•์ œํ•ด๋ด…์‹œ๋‹ค. 

Calculator c1 = new Calculator(10, 20);
c1.sum();
c1.avg();

 

์ด๋ฅผ ์œ„ํ•ด์„œ ์ฝ”๋“œ๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ณ€๊ฒฝํ•ด๋ด…์‹œ๋‹ค. 

package org.opentutorials.javatutorials.constructor;
 
class Calculator {
    int left, right;
 
    public Calculator(int left, int right) {
        this.left = left;
        this.right = right;
    }
 
    public void sum() {
        System.out.println(this.left + this.right);
    }
 
    public void avg() {
        System.out.println((this.left + this.right) / 2);
    }
}
 
public class CalculatorDemo1 {
 
    public static void main(String[] args) {
 
        Calculator c1 = new Calculator(10, 20);
        c1.sum();
        c1.avg();
 
        Calculator c2 = new Calculator(20, 40);
        c2.sum();
        c2.avg();
    }
 
}
public Calculator(int left, int right) {
    this.left = left;
    this.right = right;
}

 

์œ„ ๋ถ€๋ถ„์ด ๋ฐ”๋กœ ์ƒ์„ฑ์ž์ž…๋‹ˆ๋‹ค. ์ƒ์„ฑ์ž๋Š” ์ด๋ฆ„์ฒ˜๋Ÿผ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ํ˜ธ์ถœ๋ฉ๋‹ˆ๋‹ค. 

Calculator c1 = new Calculator(10, 20);

์ƒ์„ฑ์ž ๋•๋ถ„์— Calculator ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ์ž‘์—…์ธ left์™€ right์˜ ๊ฐ’์„ ์„ค์ •ํ•˜๋Š” ๊ณผ์ •์„ ๊ฐ์ฒด ์ƒ์„ฑ ๊ณผ์ •์—์„œ ๊ฐ•์ œํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!

 

์ƒ์„ฑ์ž์˜ ํŠน์ง•

1. ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. / ์ƒ์„ฑ์ž๋Š” ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•ด์ฃผ๋Š” ์—ญํ• ์„ ํ•˜๋Š” ํŠน์ˆ˜ํ•œ ๋ฉ”์†Œ๋“œ ์ž…๋‹ˆ๋‹ค. 

2. ์ƒ์„ฑ์ž์˜ ์ด๋ฆ„์€ ํด๋ž˜์Šค์˜ ์ด๋ฆ„๊ณผ ๋™์ผํ•ฉ๋‹ˆ๋‹ค. / ์ž๋ฐ”์—์„œ ํด๋ž˜์Šค์˜ ์ด๋ฆ„๊ณผ ๋™์ผํ•œ ๋ฉ”์†Œ๋“œ๋Š” ์ƒ์„ฑ์ž๋กœ ์‚ฌ์šฉํ•˜๊ธฐ๋กœ ์•ฝ์†๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. 

๋ฐ˜์‘ํ˜•