πŸͺJava

[Java] μžλ°” 클래슀(메인 클래슀/클래슀)

루리야ㅑ 2023. 12. 20. 12:14
λ°˜μ‘ν˜•

μžλ°” 클래슀 크게 두 κ°€μ§€λ‘œ λ‚˜λ‰œλ‹€.

- ν΄λž˜μŠ€λ₯Ό μ‹€ν–‰ν•˜λŠ” λΆ€λΆ„
- ν΄λž˜μŠ€λ₯Ό λ§Œλ“œλŠ” λΆ€λΆ„

κ·Έλž˜μ„œ 클래슀λ₯Ό λ§Œλ“€κ³  싀행은 메인 ν΄λž˜μŠ€μ—μ„œ μ‹€ν–‰λœλ‹€.

1. 클래슀 생성

λ¨Όμ € 클래슀λ₯Ό λ§Œλ“€μ–΄λ³΄μž.
number, name μ΄λΌλŠ” λ³€μˆ˜λ₯Ό μ„ μ–Έν•˜κ³ 
printλΌλŠ” return 없이 ν”„λ¦°νŠΈν•˜λŠ” ν•¨μˆ˜λ₯Ό λ§Œλ“€μ—ˆλ‹€.

public class Product {
    int number;
    String name;

    void print(){
        System.out.println(number);
        System.out.println(name);
    }

}

 

2. 메인 클래슀 생성

메인 ν΄λž˜μŠ€μ•ˆμ— κ°€μž₯ λ¨Όμ € 와야할 것은 public static void main(String[] args) ν•¨μˆ˜μ΄λ‹€.
κ·Έ ν•¨μˆ˜ λ‚΄μ—μ„œ μ‹€ν–‰ μ½”λ“œλ₯Ό λ§Œλ“€μ–΄ μ‹€ν–‰ν•œλ‹€.

λ¨Όμ € μƒμ„±μž(new ClassName)λ₯Ό λ§Œλ“€μ–΄μ„œ λ³€μˆ˜μ— μ €μž₯ν•˜κ³ 
κ·Έ λ³€μˆ˜μ—μ„œ  값을 μ΄ˆκΈ°ν™” ν•œλ‹€μŒ
μœ„μ—μ„œ λ§Œλ“  print() ν•¨μˆ˜λ₯Ό λ³€μˆ˜ κ°κ°μ—μ„œ μ‹€ν–‰ν•œλ‹€.

public class ProductMain {
    public static void main(String[] args) {

        Product p1 = new Product();
        p1.number = 1;
        p1.name = "컴퓨터";

        Product p2 = new Product();

        p2.number = 2;
        p2.name = "TV";

        // 데이터 μ•‘μ„ΈμŠ€ν•˜κ³ , 좜λ ₯

        p1.print();
        p2.print();

    }
}
λ°˜μ‘ν˜•