JAVA 프로그래밍

[JAVA] 풀스택 개발자 부트캠프 008일차 ② Class 예제 3개

selfdailycoding 2025. 1. 7. 10:51

class : 객체(변수)를 사용하기 위한 설계

형식 :
     클래스의 설계
     class 클래스명{
        변수선언부

        함수(=method)선언부  method == class 에 소속되어 있는 함수
     }

     클래스를 생성
     클래스명 객체(변수) = new 클래스명();  <- 객체를 선언
     객체.함수()


예제1) class 설계(구축) - 사용자 클래스

public class MainClass {

    public static void main(String[] args) {

        int number[] = new int[10];
        String name[] = new String[10];
        double height[] = new double[10];
        String address[] = new String[10];

        // 변수(객체)만 선언
        MyClass clsArr[] = new MyClass[10]; // MyClass clsArr1, clsArr2, clsArr3

        MyClass cls = new MyClass();    // 변수 == 객체(instance, object)를 선언
        //     stack      heap                          주체
        // delete heap;   // <- 가비지(쓰레기)컬렉터
        cls.number = 1;
        cls.name = "성춘향";
        cls.height = 156.2;

        cls.method();
class MyClass{
    int number;     // 멤버변수
    String name;
    double height;
    String address;

    void method(){
        System.out.println("MyClass method()");
    }
}

 


예제2) TV 브랜드, 채널, on/off

public class MainClass {

    public static void main(String[] args) {

        // 브랜드, 채널, on/off
        String tvname;
        int channel;
        boolean power;
        int size;

        tvname = "LG";
        channel = 15;
        power = true;
        size = 52;


        TV arrTv[] = new TV[5];  // 객체(배열)만 선언
        // TV tv = new TV();
        for (int i = 0;i < arrTv.length; i++){
            arrTv[i] = new TV();    // 객체를 생성
        }

        arrTv[0].tvname = "LG";
class TV{
    String tvname;
    int channel;
    boolean power;
    int size;

}

 


예제3) TV 브랜드, 채널, on/off

public class MainClass {

    public static void main(String[] args) {

        Dice di1 = new Dice();
        int n = di1.getNumber();
        System.out.println("dice1 = " + n);

        Dice di2 = new Dice();
        n = di2.getNumber();
        System.out.println("dice1 = " + n);
    }
}
class Dice{
    int number;
    String color;

    int getNumber(){
        number = (int)(Math.random() * 6) + 1;  // 1 ~ 6
        return number;
    }
}