Java

Java) 객체지향 프로그래밍 : 클래스와 메소드 정리

pogun 2025. 1. 5. 02:18

class : 객체를 사용하기 위한 설계

method : class에 소속되어 있는 함수

 

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

            함수(method) 선언부
        }

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

        객체.함수()


객체지향 프로그래밍 기본 예제

public class MainClass {
    public static void main(String[] args) {
    MyClass cls = new MyClass();  // 객체(instance, object)를 선언
    //     stack       heap                  주체
    cls.number = 1;
    cls.name = "일지매";
    cls.height = 251.1;
    
    cls.method();
    }
}

// 클래스 설계(클래스 선언) - 사용자 지정 클래스
class MyClass{
    int number;       // 멤버변수
    String name;      //  ...
    double height;    //  ...

    // 메소드 선언(함수 선언)
    void method(){
        System.out.println("MyClass method()");
    }
}

: MyClass의 객체 cls를 생성한다.(MyClass 클래스를 바탕으로 새로운 인스턴스를 생성하고, 그 객체를 cls에 할당)

: cls 객체의 각 변수값 설정(number, name, height)

: cls 객체에서 method() 메소드를 호출

: MyClass는 3개의 멤버 변수(number, name, height)와 1개의 메소드(method())를 가진다.

배열과 객체를 함께 사용하는 예제

public class MainClass {
    public static void main(String[] args) {
    	
        TV arrTv[] = new TV[5]; // TV 객체 배열 선언

        for(int i = 0; i < arrTv.length; i++){
            arrTv[i] = new TV();   // 각 배열 요소에 TV 객체 생성
            arrTv[i].tvName = "브랜드" + (i + 1);
            arrTv[i].channel = 10 + i;
            arrTv[i].power = (i % 2 == 0);
        }

        // TV 정보 출력
        for (int i = 0; i < arrTv.length; i++) {
            System.out.println("TV " + (i + 1) + " 정보:");
            System.out.println("브랜드: " + arrTv[i].tvName);
            System.out.println("채널: " + arrTv[i].channel);
            System.out.println("전원 상태: " + (arrTv[i].power ? "ON" : "OFF"));
            System.out.println();
        }
    }
}

class TV{
    String tvName;
    int channel;
    boolean power;
}

TV arrTv[] = new TV[5] : TV 객체를 담을 수 있는 배열을 선언(TV 객체를 5개 저장할 수 있도록 크기 설정)

: 배열을 선언만 했을 뿐, 각 배열 요소에 실제 TV 객체가 들어가 있는 것은 아니다.(기본적으로 Null값 가짐)

 

arrTv[i] = new TV() : 각 배열의 요소에 새로운 TV 객체를 생성하여 할당하는 과정

: 해당 과정이 없으면 배열의 각 요소는 여전히 null이고, 객체의 속성(TvName, Channel, power)을 설정하거나 사용할 수 없다.

랜덤 주사위

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();
    int n2 = di2.getNumber();
    System.out.println("Dice2 : " + n2);

    Dice di3 = new Dice();
    int n3 = di3.getNumber();
    System.out.println("Dice3 : " + n3); 
    }
}

class Dice{
    int number;

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

: MainClass에서 Dice 객체를 3개 생성

: di1, di2, di3 각각 Dice 객체에서 getNumber() 메소드를 호출

총점과 평균 계산 프로그램

public class MainClass {
    public static void main(String[] args) {
  	
    Student s = new Student();

    s.name = "홍길동";
    s.kor = 100;
    s.eng = 60;
    s.math = 76;

    System.out.println("이름:"+ s.name);
    System.out.println("총점:"+ s.getTotal() );
    System.out.println("평균:"+ s.getAverage( ) );
    }
}

class Student{
    String name;
    int kor;
    int eng;
    int math;

    int getTotal(){
        return kor + eng + math;
    }

    double getAverage(){
        return Math.round((getTotal() / 3.0));
    }
}

: Student 클래스에 멤버 변수 선언과 getTotal(), getAverage() 메소드 작성

: 총점을 계산한 메소드를 평균 계산 메소드에 사용할 수 있다.

TV 채널과 볼륨을 설정하고 출력

public class MainClass {
    MyTv2 t = new MyTv2();

    t.setChannel(10);
    System.out.println("CH:"+ t.getChannel());
    t.setVolume(20);
    System.out.println("VOL:"+ t.getVolume());
    }
}

class MyTv2{
    int channel;
    int volume;

    void setChannel(int ch){
        channel = ch;
    }

    int getChannel(){
        return channel;
    }

    void setVolume(int vo){
        volume = vo;
    }

    int getVolume() {
        return volume;
    }
}

set 메소드 : 값을 설정하는 역할(보통 리턴하지 않음)

: 메소드 내에서 객체의 속성 값을 변경하고, 그 변경된 값을 외부로 전달하지 않는다. 대신, 해당 메소드가 호출되면 객체의 상태가 변경된다.

 

get 메소드 : 값을 가져오고 반환하는 역할(리턴 함)

: 메소드 내에서 객체의 속성 값을 가져와 반환한다. 이때, 외부에서 그 값을 사용할 수 있도록 반환하는 것이 특징이다.

 

차이점 요약 :

set 메소드 : 값을 설정만 하고, 리턴하지 않는다.

ex) setChannel(int ch) -> channel 값을 설정

 

get 메소드 : 값을 가져오고, 리턴한다.

ex) getChannel() -> Channel 값을 반환

주사위 맞추기 게임 프로그램

public class MainClass {
    Game game = new Game();
    game.play();
}

class Game{
    int comNumber;
    int user;
    boolean clear;
    int win = 0;
    int lose = 0;

    Scanner sc = new Scanner(System.in);

    void init(){
        clear = false;
        comNumber = (int)(Math.random() * 6) + 1;
    }

    void userInput(){
        System.out.print("수 예측 : ");
        user = sc.nextInt();
    }

    void finding() {
        if (user == comNumber) {
            clear = true;
            win++;
        } else{
            lose++;
        }
    }

    void result(){
        System.out.println("정답 : " + comNumber);

        if(clear == true){
         System.out.println("맞추셨습니다! 축하합니다!");

        } else {
             System.out.println("틀렸습니다! 다시 도전하세요!");
        }

        System.out.println("전적은 "+ win + "승" + lose + "패 입니다.");
    }

    void play(){
        while(true) {
            init();
            userInput();
            finding();
            result();

            System.out.print("다시 도전 하시겠습니까? (y/n) = ");
            String msg = sc.next();
            if(msg.equals("n") || msg.equals("Y")){
                System.out.println("게임을 종료합니다.");
                break;
            } else {
                System.out.println("다시 시작합니다!");
            }
        }
    }
}

: MainClass에서 Game 객체를 생성하고, game.play()를 호출하여 게임을 시작

: 해당 로직을 살펴보면 Game 클래스에서 각각 실행하는 메소드들을 구현

: 그 후 메인 루프인 play에 메소드를 넣음.

: MainClass에서는 play만 호출하면 Game 클래스에서 모두 처리하도록 설계하는 방법