관리 메뉴

βœπŸ»κΈ°λ‘ν•˜λŠ” λΈ”λ‘œκ·Έ

μ•„μ΄ν…œ 16. public ν΄λž˜μŠ€μ—μ„œλŠ” public ν•„λ“œκ°€ μ•„λ‹Œ μ ‘κ·Όμž λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜λΌ λ³Έλ¬Έ

μΉ΄ν…Œκ³ λ¦¬ μ—†μŒ

μ•„μ΄ν…œ 16. public ν΄λž˜μŠ€μ—μ„œλŠ” public ν•„λ“œκ°€ μ•„λ‹Œ μ ‘κ·Όμž λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜λΌ

μ©μ‹œν‚΄ 2022. 12. 26. 21:34
728x90
  • public ν΄λž˜μŠ€λŠ” ν•„λ“œλ₯Ό 직접 λ…ΈμΆœν•˜μ§€ 말 것.
    • 객체지ν–₯ ν”„λ‘œκ·Έλž˜λ°μ—μ„œλŠ” ν•„λ“œλ₯Ό private둜 μ„ μ–Έν•˜κ³ , getterλ₯Ό μΆ”κ°€ν•œλ‹€.
public class Main {
    public double x;
    public double y;

    public static void main(String[] args) {
        Main main = new Main();
        main.x = 10;
        main.y = 10;
        System.out.println(main.x);
        System.out.println(main.y);
    }
}

μœ„μ™€ 같은 μ½”λ“œλŠ” μΊ‘μŠν™”μ˜ μž₯점을 μ œκ³΅ν•˜μ§€ λͺ»ν•œλ‹€.

ν•„λ“œμ— μ ‘κ·Όν•˜λŠ” 방식을 λ©”μ„œλ“œλ‘œ μ§€μ •ν•˜λ©΄ ν•„λ“œλͺ…이 λ³€κ²½λ˜μ–΄λ„ λ©”μ„œλ“œ λͺ…을 λ°”κΏ€ ν•„μš”λŠ” 없어진닀. λ˜ν•œ λ©”μ„œλ“œ μ•ˆμ—μ„œ 뢀가적인 μž‘μ—…λ„ κ°€λŠ₯해진닀.
단, package-private, private 쀑첩 클래슀라면 데이터 ν•„λ“œλ₯Ό λ…ΈμΆœν•΄λ„ λ¬΄λ°©ν•˜λ‹€.

public class Main {
    private double x;
    private double y;

    public Main(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double getX() {
        //λΆ€κ°€μž‘μ—…
        return x;
    }
    public double getY() {return y;}

    public void setX(double x) {
        //λΆ€κ°€μž‘μ—…
        this.x = x;
    }
    public void setY(double y) {this.y = y;}
}

λ§Œμ•½ public으둜 μ„ μ–Έν•œ ν•„λ“œλ“€(가변적)을 μ•ˆμ „ν•˜κ²Œ μ“°κΈ° μœ„ν•΄ ν•„λ“œκ°€ μ‚¬μš©λ˜λŠ” λ²”μœ„ μ•ˆμ—μ„œ 값을 λ³΅μ‚¬ν•˜μ—¬ μ‚¬μš©ν•΄μ•Ό ν•œλ‹€.

ν•˜μ§€λ§Œ μΈμŠ€ν„΄μŠ€λ₯Ό λ§Œλ“œλŠ” 방법은 λΆˆν•„μš”ν•œ μΈμŠ€ν„΄μŠ€λ₯Ό λ§Œλ“œλŠ” κ²ƒμ΄λ―€λ‘œ μ„±λŠ₯μ €ν•˜ μš”μΈμ΄ 될 수 μžˆλ‹€.

public class Main {
    public double x;
    public double y;

    public static void main(String[] args) {
        Main main = new Main();
        main.x = 10;
        main.y = 10;

        doSomething(main);

        System.out.println(main.x);
        System.out.println(main.y);
    }

    private static void doSomething(Main main) {
        Main localMain = new Main();
        localMain.x = main.x;
        localMain.y = main.y;
    }
}

μžλ°” ν”Œλž«νΌ λΌμ΄λΈŒλŸ¬λ¦¬μ—λ„ public 클래슀의 ν•„λ“œλ₯Ό 직접 λ…ΈμΆœν•˜μ§€ μ•Šμ•„μ•Ό ν•˜λŠ” κ·œμΉ™μ„ μ–΄κΈ΄ 사둀가 μ‘΄μž¬ν•œλ‹€.

java.awt.package의 Dimension, Pointν΄λž˜μŠ€μ΄λ‹€.

728x90
λ°˜μ‘ν˜•