STUDY/languages

[자바] 메소드, 클래스 정리

이앤지 2021. 11. 17. 20:42

메소드

더보기
package day0914;
/*메소드
 * 
 * 메소드란, 여러 줄의 코드를 합쳐서
 * 하나의 기능으로 만들어 놓은 것을 메소드라고 한다.
 * 
 * 예를 들어서, 우리가 Scanner 클래스 변수의
 * nextInt() 라는 메소드를 실행했을 때,
 * 우리가 적은 것은 한줄에 불과하지만, (scaner.nextInt())
 * 실제로는, 해당 메소드 안에 적혀있는 모든 코드들이 차례대로 실행이 되는 구조이다.
 * 즉, 하나의 단축이라고도 할 수 있게 되는 것이다.
 * 
 * 예를 들어서
 * 우리가 "라면 끓여와" 라는 메소드를 실행하게 된다면
 * 실제로는
 * 1. 라면을 준비한다.
 * 2. 냄비를 준비한다.
 * 3. 냄비에 물을 넣는다.
 * 4. 냄비를 가스렌지 위에 올린다.
 * 5. 라면 봉지를 연다.
 * 6. 물이 끓으면 라면 봉지의 내용물을 냄비에 넣는다.
 * 7. 면이 익으면 그릇에 붙는다.
 * 
 * 메소드의 경우, 우리가 선언과 구현으로 나눌 수가 있는데
 * 클래스의 경우, 메소드는 반드시 선언과 구현이 같이 이루어져야 한다.
 * 
 * 메소드의 선언은 다음과 같이 이루어진다.
 * 접근제한자 (static) 리턴타입 메소드이름(파라미터)
 * 
 * 접근제한자: 해당 메소드를 외부 클래스가 접근할 때
 *         어디에 있는 외부 클래스가 접근 가능한지 설정하는 키워드.
 *         Access Modifier라고 한다.
 *         접근제한자는 public, protected, package, private 4종류가 있다.
 *         public: 다른 패키지에 있는 다른 클래스도 실행 가능
 *         protected: 같은 패키지에 있는 다른 클래스는 실행 가능
 *                    다른 패키지에 있는 클래스의 경우 상속관계 일때에만 실행 가능
 *         package: 같은 패키지에 있는 다른 클래스들만 실행 가능.
 *                  단, 패키지 접근 제한자는 우리가 아무런 접근제한자를 적어주지 않을 때에만 적용된다.// 지금 클래스 package day0914여기서 daypo14때문에 아님
 *         private: 다른 패키지는 어디에 있던간에 실행할 수 없다.
 *                  즉, 해당 클래스만 실행 가능하다.
 *                  
 * static: static 키워드는 해당 메소드를 클래스 변수를 선언하지 않고 사용할 수 있게 한다.
 *         예를 들어서, 만약 우리가 기존에 사용하던 Scanner 클래스의 nextInt() 메소드에
 *         static 키워드가 붙어있다면, Scanner scanner = new Scanner(System.in) -> scanner.nextInt() 로 사용하는 것이 아니라
 *         Scanner.nextInt()의 방식으로 사용하게 되는 것이다.
 *         static 키워드는 우리가 생략할 수 있지만 만약 static 메소드가 다른 메소드를 곧장 호출할 때에는 그 다른 메소드에도 static이 반드시
 *         붙어야 한다.
 *         
 * 리턴타입: 리턴 타입이란, 해당 메소드가 종료될 때 호출된 곳으로 보내줄 값의 데이터타입을 말한다.
 *        예를 들어서. 스캐너 클래스의 nextInt() 메소드는 리턴 타입이 int라고 적혀있고, 내부적으로 코드를 모두다 실행 시킨 후에는
 *        int 타입의 값을 호출한 곳으로 보내주는 형태가 된다.
 *        리턴 타입이 존재할 시에는 해당 메소드의 내부에서 반드시 return이라는 키워드를 통해서 해단 데이터타입과 일치하는 값을
 *        "리턴"해 주어야 한다.
 *        만약 해당 메소드가 아무런 값도 리턴하지 않을 때에는 리턴 타입에 void라고 적어야 하며 이때에는 오히려
 *        return 키워드를 적으면 에러가 발생한다.
 *        
 * 메소드 이름: 소문자로 시작하고 낙타등 표기법을 따르는 동사
 * 
 * 파라미터: 파라미터란, 해당 메소드를 실행시킬 때 필요하여 외부로부터 받아오는 값을 변수로 선언해둔 것이다.
 *        예를 들어서, 우리가 라면끓이기() 라는 메소드를 실행하기 위해서는 "라면 진라면", "냄비 양은냄비" 이런 식으로
 *        재료가 필요하듯,
 *        메소드를 실행시킬 때 외부로부터 받아올 값을 우리가 변수로 만든 것이다.
 *        그렇기 때문에 한국말로는 "매개변수"라고도 한다.
 * 
 */

public class Ex06Method {
    // 메인메소드 main+ctrl+enter. 단축키
    // public static void main(String[] args) { }
    // 접근제한자//키워드 //리턴타입 //파 라 미 터

    public static void main(String[] args) {
        
        
        printNum(); //반복되는 코드는 귀찮으니깐 함수로 만듦.
        
//        String name = "조재영";
//        System.out.println(name+"1");
//        System.out.println(name+"2");
//        System.out.println(name+"3");
//        System.out.println(name+"4");
//        System.out.println(name+"5");
//        System.out.println(name+"6");
//
//        name = "김철수";
//        System.out.println(name+"1");
//        System.out.println(name+"2");
//        System.out.println(name+"3");
//        System.out.println(name+"4");
//        System.out.println(name+"5");
//        System.out.println(name+"6");

        //호출하는 방법
//        String name = "조재영";
//        printName(name);
//
//        printName("김철수");
//        
//        String str = "이영희";
//        
//        printName(str);

        int num = selectNum();
       
//        int num;
//        System.out.println("selectNum() 실행");
//        System.out.println("이런 저런 코드 실행");
//        System.out.println("최종 결과값 5를 호출된 곳으로 보내준다.");
//        num = 5;
//        
        System.out.println("num의 현재 값: "+num);
        
    }

    public static void printNum() {// 리턴도 없고 파라미터도 없는 함수
        System.out.println(1);
        System.out.println(2);
        System.out.println(3);
        System.out.println(4);
        System.out.println(5);
        System.out.println(6);

    }
    
    public static void printName(String name) {
        
        System.out.println(name+"1");
        System.out.println(name+"2");
        System.out.println(name+"3");
        System.out.println(name+"4");
        System.out.println(name+"5");
        System.out.println(name+"6");
    }
    
    public static int selectNum() {
        System.out.println("selectNum() 실행");
        System.out.println("이런 저런 코드 실행");
        System.out.println("최종 결과값 5를 호출된 곳으로 보내준다.");
        return 5;
    }

}

 

메소드 오버로드

더보기
package day0914;
/*메소드 오버로드
 * 
 * 오버로드란, 똑같은 목적을 가지고 있을 경우,
 * 메소드의 이름을 통일 시켜서 코드의 가독성을 높여주는 방법이다.
 * 하지만 똑같은 이름의 메소드를 만들 때 주의할 점이 있는데,
 * 반그시 파라미터의 내용이 달라야 한다는 것이다!
 * 
 */

public class Ex08Overload {
    public static int add(int a, int b) {
        return a+b;
        
    }
    
    public static double add(double a, double b) {
        return a+b;
    }
    
    public static double add(int a, double b) {
        return a+b;
    }
    
    
    public static void main(String[] args) {
   
        System.out.println(add(3,4));
        
        System.out.println(add(3.0, 4.0));

    }

}

 

전역변수

/*전역변수 (Global Variable)
 * 전역 변수란, 프로그램 전체에서 접근 가능한 변수이다.
 * 우리가 기존에 사용하던 변수는 메인 메소드 내부에서만 사용 가능 했지만,
 * 전역 변수는 메인 메소드 뿐만이 아니라 다른 메소드에서도 해당 변수에 값을 저장하거나
 * 저장된 값을 호출 할 수 있다.
 * 
 * 전역 변수의 장점: 어디서든 접근 가능하다.
 * 전역 변수의 단점: 어디서든 접근 가능하다.
 */

 

 

/*call by value 와 call by reference의 차이
 * 메소드를 우리가 호출할 때 파라미터로 값을 넘기는 경우
 * 두 가지 방법으로 값이 넘어가게 된다.
 * 
 * 기본형 데이터타입의 경우, 해당 변수 혹은 값이 복사 되서 넘어간다.
 * 즉 복사된 값이 넘어가므로 "값에 의한 호출" 혹은 call by value라고 한다.
 * (원본에 영향을 주지 않음!)
 * 
 * 참조형 데이터타입의 경우, 해당 변수 혹은 값의 주소값이 넘어간다.
 * 즉 참조 가능한 주소값이 넘어가므로 "참조에 의한 호출" 혹은 call by reference라고 한다.
 * (값의 주소값이 넘어가니깐 원본에 영향을 끼치게 된다.)
 */

더보기
public class Ex01MethodCall {
    // call by value가 발생하는
    // callVyBal 메소드
    // 파라미터는 int a
    public static void callByVal(int a) {
        System.out.println("callByVal(int) 호출");
        a = 30;
        a++;
        System.out.println("a의 현재값: " + a);
    }
    
    // call by reference가 발생하는
    // callByRef 메소드
    // 파라미터는 int[] arr
    public static void callByRef(int[] arr) {
        System.out.println("callByRef(int[]) 호출");
        arr[0] = 25;
        arr[0]++;
        System.out.println("arr[0]의 현재값: "+arr[0]);
    }
    
    // call By Refefence를 사용하기 위해
    // 참조형 데이터를 파라미터로 받아올 경우
    // 다음과 같은 경우에는 원본에 아무런 영향을 미치지 않는다.
    public static void insertNewAddr(int[] arr) {
        System.out.println("insertNewAddr(int[]) 호출");
        arr = new int[7];
        System.out.println("arr의 현재 길이: "+ arr.length);
    }
    
    
    public static void main(String[] args) {
        //int 변수 선언
        int b = 40;
        System.out.println("b의 현재값: "+b);
        
        callByVal(b);
        
        System.out.println("b의 현재값: "+b);
        
        
        //int[] 변수 선언
        int[] arr = new int[3];
        arr[0] = 7;
        System.out.println("arr[0]의 현재값: "+ arr[0]);
        
        callByRef(arr);
        
        System.out.println("call by refence 이후 arr[0]의 현재값: "+arr[0]);
        
        System.out.println("arr의 현재 길이: " + arr.length);
        insertNewAddr(arr);
        System.out.println("arr의 현재 길이: " + arr.length);

        
    }

}

 

문제

1. /* 퀴즈 제한시간 20분
 * Call By Reference를 사용하여
 * 학생의 정보를 입력하는 코드를 메소드로 분리하세요.
 * 
 * Call By Value를 사용하여
 * 메뉴를 출력하는 코드를 메소드로 분리하세요
 * 힌트: 사용자가 선택한 값을 어떻게 메인으로 넘겨주어야 할까?
 * 
 * 즉, 해당 프로그램에는
 * 1. 메뉴를 출력하고 사용자의 선택을 메인으로 넘겨주는 메소드
 * 2. 학생의 정보를 입력하는 메소드
 * 3. 학생의 정보를 출력하는 메소드
 * 3개의 메소드가 있어야 한다.
 */

더보기
package day0915;

import java.util.Scanner;

public class Ex02GradeBook01 {

    // 썜이한거
    public static void main(String[] args) {

        // 상수
        final int SUBJECT_SIZE = 3;
        final int STUDENT_SIZE = 5;

        // 변수
        Scanner scanner = new Scanner(System.in);
        int[] idArray = new int[STUDENT_SIZE];
        String[] nameArray = new String[STUDENT_SIZE];
        int[][] scoreArray = new int[STUDENT_SIZE][SUBJECT_SIZE];

        int curIndex = 0; // 다음에 입력할 위치

        while (true) {
            // 메뉴 출력 및 사용자 선택을 결정하는 메소드 호출
            int userChoice = showMenu(scanner);

            if (userChoice == 1) {
                // 입력 담당 코드 구현
                if (curIndex < STUDENT_SIZE) {
                    // 입력 가능하므로 입력 메소드 실행
                    insertInfo(scanner, idArray, nameArray, scoreArray, curIndex);
                    // 다음 입력 위치를 1 증가시킨다.
                    curIndex++;

                } else {
                    // 더이상 입력할 수 없으므로 경고메시지만 출력
                    System.out.println("더이상 입력하실 수 없습니다.");
                }

            } else if (userChoice == 2) {
                // 출력 코드 구현
                if (curIndex == 0) {
                    System.out.println("아직 입력된 학생이 존재하지 않습니다.");
                } else {
                    // 출력 메소드 실행
                    printAll(idArray, nameArray, scoreArray, curIndex, SUBJECT_SIZE);

                }

            } else if (userChoice == 3) {
                // 종료
                System.out.println("사용해주셔서 감사합니다.");
                break;

            }

        }

        scanner.close();

    }

    public static int showMenu(Scanner scanner) { // 스캐너를 여기서 함수내에서 또 만들어도 되지만 개비효율적이니깐 위의 스캐너값을 받아옴!
        System.out.println("1.입력 2.출력 3.종료");
        System.out.println("> ");
        int userChoice = scanner.nextInt();

        return userChoice; //
    }

    public static void insertInfo(Scanner scanner, int[] idArray, String[] nameArray, int[][] scoreArray,
            int curIndex) {

        // 번호 입력
        System.out.println("번호를 입력해주세요.");
        System.out.println("> ");
        idArray[curIndex] = scanner.nextInt();

        // 이름 입력
        System.out.println("이름을 입력해주세요.");
        System.out.println("> ");
        scanner.nextLine();
        nameArray[curIndex] = scanner.nextLine();

        /*
         * 2차원 배열 scoreArray의 1차원 배열에 0번 칸에는 국어 1번 칸에는 영어 2번 칸에는 수학을 저장한다.
         */

        System.out.println("국어 점수를 입력해주세요.");
        System.out.println("> ");
        scoreArray[curIndex][0] = scanner.nextInt();

        System.out.println("영어 점수를 입력해주세요.");
        System.out.println("> ");
        scoreArray[curIndex][1] = scanner.nextInt();

        System.out.println("수학 점수를 입력해주세요.");
        System.out.println("> ");
        scoreArray[curIndex][2] = scanner.nextInt();

    }

    public static void printAll(int[] idArray, String[] nameArray, int[][] scoreArray, int curIndex, int SUBJECT_SIZE) {

        // 출력
        for (int i = 0; i < curIndex; i++) {
            System.out.println("-------------------");
            System.out.println(nameArray[i] + " 학생의 정보");
            System.out.println("-------------------");

            int id = idArray[i];
            String name = nameArray[i];
            int korean = scoreArray[i][0];
            int english = scoreArray[i][1];
            int math = scoreArray[i][2];

            int sum = korean + english + math;

            double average = (double) sum / SUBJECT_SIZE;

            System.out.printf("번호: [%d]번  이름: [%s]\n ", id, name);
            System.out.printf("국어: [%03d]점 영어: [%03d]점 수학: [%03d]점\n", korean, english, math);
            System.out.printf("총점: [%03d]점 평균: [%06.2f]점\n", sum, average);

            System.out.println("===========================\n");

        }   
    }

}

 

2. /*퀴즈 20분
 * 출력은 자유! 
 * 사용자가 넘겨주는 int 값 2개를
 * 사칙 연산을 예쁘게 출력하고(예: 5x3 = [15])
 * 그 결과값을 리턴하는 메소드 5개를 만들고
 * 메인 메소드에서 사용자가 키보드 입력을 통해
 * 입력한 int 값 2개에 대한 메소드 결과를 실행시키는
 * 코드를 작성하시오
 * 단, 나눗셈의 경우 결과가 double로 나올 수 있게
 * 작성하시오.
 */

더보기
package day0914;

import java.util.Scanner;

public class Ex07Calculator {
    // 쌤이 한거
    // 더하기 담당 메소드
    public static int add(int a, int b) {
        System.out.println("===============");
        System.out.println("\t더하기 메소드");
        System.out.println("===============");
        System.out.printf("%d + %d = [%d]\n", a, b, a + b);
        System.out.println("---------------\n");

        return a + b;
    }

    // 빼기 담당 메소드
    public static int substract(int a, int b) {
        System.out.println("===============");
        System.out.println("\t빼기 메소드");
        System.out.println("===============");
        System.out.printf("%d - %d = [%d]\n", a, b, a - b);
        System.out.println("---------------\n");

        return a - b;
    }

    // 곱하기 담당 메소드
    public static int multiply(int a, int b) {
        System.out.println("===============");
        System.out.println("\t곱하기 메소드");
        System.out.println("===============");
        System.out.printf("%d * %d = [%d]\n", a, b, a * b);
        System.out.println("---------------\n");

        return a * b;
    }

    // 나누기 담당 메소드
    public static double divide(int a, int b) {
        System.out.println("===============");
        System.out.println("\t나누기 메소드");
        System.out.println("===============");
        System.out.printf("%d / %d = [%.3f]\n", a, b, (double) a / b);
        System.out.println("---------------\n");

        return (double) a / b;
    }

    // 나머지 담당 메소드
    public static int remain(int a, int b) {
        System.out.println("===============");
        System.out.println("\t나머지 메소드");
        System.out.println("===============");
        System.out.printf("%d %% %d = [%d]\n", a, b, a % b);
        System.out.println("---------------\n");

        return a % b;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("첫번째 숫자를 입력해주세요.");
        System.out.println("> ");
        int num1 = scanner.nextInt();
        
        System.out.println("두번째 숫자를 입력해주세요.");
        System.out.println("> ");
        int num2 = scanner.nextInt();
        
        add(num1, num2);
        substract(num2, num1);
        multiply(num1, num2);
        divide(num1, num2);
        remain(num1, num2);

        
        //순서 생각해보기.
        //add(2,3) add(4,5)각각 변수로 활용이 가능
        add(add(2,3), add(4,5));
        
        
        scanner.close();
        
        

        //지금 같은 경우 리턴타입을 void로 해도 상관이 없으띾?
        //=>문제 없음. 나온 결과값 어디 안쓰니깐.
    }

}

 

 


클래스

더보기
package day0917;
/*클래스
 * 우리가 기존에는 정보를 입력하는 공간과 기능을 분리해서 만들어 놓았다.
 * 예를 들어서, 학생의 정보는 우리가 최종적으로 구조체 라는 것을 사용하여
 * 학생의 정보를 넣을 데이터타입을 규정을 하고,
 * 기능은 따로 만들었었다.
 * 이러한 방법은 2세대 언어에서 사용이 된 방법인데, 왜냐하면 2세대 언어에서는
 * 프로그램을 "기능의 집한" 으로 보았기 때문이다.
 * 그래서 우리가 최종적으로 구조체 배열과 메인 메소드를 제외한 다른 메소드를 만들어서
 * 따로 따로 사용을 했던 것이다.
 * 
 * 하지만 왜 학생의 정보를 넣을 공간과 기능을 분리해야 하는가?
 * 3세대 언어에서는 만약 학생을 관리하는 프로그램을 만든다고 할 시에는
 * 학생의 정보를 저장할 공간 + 그 정보를 사용하는 기능을 합쳐서 하나의 프로그램으로 만들고
 * 우리가 실행할 프로그램에서는 그 학생 프로그램을 하나의 변수처럼 다루자가 주된 목표가 된다.
 * 
 * 즉, 구조체와 기능이 합쳐져서 하나의 온전한 클래스가 만들어지고,
 * 우리가 필요하면 그 클래스의 변수를 우리 프로그램에서 활용핳자 라는 것이 목표가 된다.
 * 즉, 3세대 언어, 객체 지향 언어에서는
 * 프로그램을 더 작은 프로그램들의 집합으로 보게 되는 것이다.
 * 
 * 객체란 무엇인가?
 * 객체란 클래스변수를 객체라고 한다.
 * 클래스 변수 -> 객체
 * 예전에 선생님 말씀중에 예를 들어서 Scanner 변수 하나 만들어줍시다!
 * Scanner sc = new Scanner(System.in)입력하는데 이게 바로 객체다)
 *
 * 클래스의 구성
 * 클래스는 필드와 메소드로 이루어져 있다.
 * 필드: 해당 클래스 변수가 가지고 있을 데이터들의 종류(구조체 같은거)
 * 메소드: 해당 클래스 변수들이 실행 가능한 기능들
 * 
 * 
 * static 키워드
 * static 키워드는 해당 메소드 혹은 필드를 클래스 변수의 선언 없이 사용하게 만든다.
 * 객체지향 프로그래밍에서는, 객체 즉 클래스 별수를 만들어서 우리가 활용하는게 지향점이다.
 * 즉, static 키워드가 사용되는 순간, 우리가 객체 지향 프로그램이이 아니라,
 * 2세대 언어, 즉 절차 지향적 프로그래밍을 하게 되는 것이다.
 * 따라서 우리는 static 키워드의 사용을 최소한으로 해야한다.
 * 
 * 수정후)
 * 최종적으론, 객체 선언 없이 사용되는 소수의 메소드. 필드를 제외하고서는
 * 그 어디에서도 static 키워드는 존재하지 않아야 한다!
 * (수정전.최종적으론, ScannerUtil과 main 메소드를 제외한 그 어디에도 static 키워드는 존재하지 않아야 한다.)
 * 
 * 
 * 생성자(Constructor)
 * 생성자란 특수한 메소드로써, 해당 클래스의 변수가 초기화 될때
 * 호출되는 메소드이다.
 * 만약 우리가 해당 클래스 변수를 초기화할 때 해주어야할 작업(=실행할 코드)가 존재할 시에는
 * 생성자를 사용하면 된다.
 * 
 * 만약 우리가 우리가 생성자를 따로 만들지 않을 경우에는
 * 자바가 제공해주는 기본 생성자를 사용하게 되는데
 * 이 기본 생성자는 해당 객체의 필드값을 기본형 데이터타입이면 0
 * 참조형 데이터타입이면 null로 초기화한다.
 * 
 * 우리가 직접 생성자를 만들어 줄때는 다음과 같이 만들어주면 된다.
 * public 클래스이름(){
 *      초기화시 실행할 코드
 * }
 * 
 * 생성자를 우리가 만들어 주면, 더이상 자바가 제공해주는
 * 기본 생성자는 사용할 수 없다.
 * 
 * 또한, 우리가 생성자에 파라미터를 넣어줄 수도 있는데,
 * 주의할 점은 만약 파라미터가 생성자만 만들어주면
 * 더이상 파라미터 없는 생상자는 사용할 수 없다(예시: Scanner 객체)
 * 
 * 
 * this
 * this 키워드는 해당 메소드를 실행시키는 객체 자신을 가리키는 대명사 와 같은 키워드이다.
 * 이 this라는 키워드는 우리가 클래스 내부에서 메소ㄷ를 만들어줄 때 자주 사용이 되는데
 * 왜냐하면 메소드 안에서 파라미터 혹은 변수가 필드와 같은 이름일 경우,
 * 우리가 해당 이름을 호출하면 무조건 파라미터/ 변수가 호출되기 때문이다.
 * 
 */

//import java.util.Scanner;
//import util.ScannerUtil;

import classEx.Student;

public class Ex02Class {
    public static void main(String[] args) {
        //static 키워드 설명 예제
//        Scanner scanner = new Scanner(System.in); //스캐너 객체
//        ScannerUtil util = new ScannerUtil();     //스캐너 유틸 객체
//        String num = util.nextLine(scanner, "abc"); 
//        //=>노란 줄이 뜨는 이유? Static방법으로~~
//        //즉, 객체를 만들어서 쓰라는게 아니고 ScannerUtil.nextLine(scanner, "abc"); 이렇게 쓰라는거
        
        // Student 클래스의 객체를 만들어보자!
        Student s1 = new Student();
        
        s1.printInfo();
        //this
        s1 = new Student(4, "ddd", 44, 44, 45);
        s1.printInfo();
        
        
        // Student 객체 s1에 값을 입력해보자.
        // 이때에는 "해당 객체의" 내부 필드 혹은 메소드르 접속할 때 사용하는
        // 접속연산자 . 을 사용하면 된다.
        s1.id = 1;
        s1.name = "조재영";
        s1.korean = 80;
        s1.english = 80;
        s1.math = 81;
        
        // s1의 내부 정보를 출력해보자.
        // 기존에는 우리가 이 메인 메소드가 있는 클래스에 따로 static 메소드를 만들어주거나
        // 아니면 모든 코드를 직접 적어주었지만 이제는 해당 클래스 안에 정의되어 있는
        // 메소드를 객체가 실행시키면 된다.
        s1.printInfo();
        
        // 또 다른 Student 객체를 만들어서 정보를 입력해보자.
        Student s2 = new Student();
        s1.id = 2;
        s1.name = "김철수";
        s1.korean = 90;
        s1.english = 90;
        s1.math = 91;
        
        // s2의 printInfo()를 실행시켜보자
        s2.printInfo();
        
        
        //------
        //equals() 비교하기
        //equals()의 경우, 우리가 클래스 안에
        //새로 정의해주지 않으면
        //부정확한 값이 나온다.
        //이유는 나중에~ 나중에~~~ => 다형성과 연결이됨!
        
        System.out.println("----------------\n");
        s1 = new Student(4, "ddd", 44, 44, 45);
        s2 = new Student(4, "ddd", 44, 44, 45);

        s1.printInfo();
        s2.printInfo();
        
        System.out.println("s1.equals(s2): "+s1.equals(s2));
        
    }

}

클래스 예제

더보기
package day0917;
/*구조체가 아닌 클래스
 * Student를 사용한 학생관리 프로그램
 * 
 */

import java.util.Scanner;

import classEx.Student;
import util.ScannerUtil;
import util.ArrayUtil;


public class Ex03GradeBook02 {
    // 상수
    //static final int SUBJECT_SIZE = 3;
    static final int STUDENT_MAX = 5;
    static final int SCORE_MIN = 0;
    static final int SCORE_MAX = 100;

    // 변수
    static Scanner scanner = new Scanner(System.in);
    static Student[] arr = new Student[0];
    // 다음 입력할 학생의 번호를 저장한 변수
    static int nextId = 1; 

    // 메인 메소드
    public static void main(String[] args) {
        showMenu();
    }

    // 메뉴를 담당하는 showMenu()
    public static void showMenu() {
        while (true) {
            System.out.println("----------------------\n");
            System.out.println("학생 관리 프로그램");
            System.out.println("----------------------\n");

            String message = "1.입력 2.출력 3.종료";
            int userChoice = ScannerUtil.nextInt(scanner, message);

            if (userChoice == 1) {
                // 입력 메소드 호출
                insert();
            } else if (userChoice == 2) {
                // 목록 출력 메소드 호출
                printAll();
            } else if (userChoice == 3) {
                System.out.println("사용해주셔서 감사합니다.");
                scanner.close();
                break;
            }
        }
    }

    // 입력을 담당하는 insert()
    public static void insert() {
        if (ArrayUtil.size(arr) < STUDENT_MAX) {

            // 입력 받은 정보를 임시로 저장할 Student 변수
            Student s = new Student();

            // 입력시 출력할 메시지를 담은 String 변수
            String message;

            // 번호 입력
            s.id = nextId++;

            // 이름 입력
            message = "학생의 이름을 입력해주세요";
            s.name = ScannerUtil.nextLine(scanner, message);

            // 국어 입력
            message = "학생의 국어 점수를 입력해주세요";
            s.korean = ScannerUtil.nextInt(scanner, message, SCORE_MIN, SCORE_MAX);

            // 영어 입력
            message = "학생의 영어 점수를 입력해주세요";
            s.english = ScannerUtil.nextInt(scanner, message, SCORE_MIN, SCORE_MAX);

            // 수학 입력
            message = "학생의 수학 점수를 입력해주세요";
            s.math = ScannerUtil.nextInt(scanner, message, SCORE_MIN, SCORE_MAX);

            // 배열에 s 추가
            arr = ArrayUtil.add(arr, s);
        } else {
            System.out.println("---------------------\n");
            System.out.println("더 이상 입력하실 수 없습니다");
            System.out.println("---------------------\n");

        }

    }

    // 학생 목록 출력을 담당하는 printAll()
    public static void printAll() {
        if (ArrayUtil.isEmpty(arr)) {
            System.out.println("-----------------------\n");
            System.out.println("아직 입력된 학생이 존재하지 않습니다.");
            System.out.println("-----------------------\n");
        } else {
            System.out.println("-----------------------\n");
            for (int i = 0; i < ArrayUtil.size(arr); i++) {
                System.out.printf("%d. %s\n", i + 1, ArrayUtil.get(arr, i).name);
            }

            System.out.println("-----------------------\n");
            String message = "개별 보기할 학생의 번호나 뒤로가시려면 0을 입력해주세요.";
            int userChoice = ScannerUtil.nextInt(scanner, message, 0, ArrayUtil.size(arr)) - 1;
            
            if(userChoice != -1) {
                printOne(userChoice);
            }
        }
    }

    // 개별 학생 출력을 담당하는 printOne()
    public static void printOne(int index) {
        Student s = ArrayUtil.get(arr, index);

//        int sum = s.korean + s.english + s.math;
//        double average = (double) sum / SUBJECT_SIZE;
        //위에거 이제 한줄 컷
//        s.printInfo();

        
        System.out.println("---------------------------\n");
        System.out.println(s.name + "학생의 정보");
        System.out.println("\n---------------------------\n");

//        //객체지향언어 -> 아래 출력문 조차 메소드로!
//        System.out.printf("번호: %d번 이름: %s\n", s.id, s.name);
//        System.out.printf("국어: %03점 영어:%03점 수학:%03점\n", s.korean, s.english, s.math);
//        System.out.printf("총점: %03점 평균: %06.2f점\n", sum, average);
        
        s.printInfo();
        
        
        String message = "1.수정 2.삭제 3.뒤로가기";
        int userChoice = ScannerUtil.nextInt(scanner, message, 1, 3);
        if(userChoice == 1) {
            //수정 메소드 호출
            update(index);
        } else if(userChoice ==2) {
            //삭제 메소드 호출
            delete(index);
        } else if(userChoice ==3) {
            printAll();
        }

    }
    
    //학생 정보 수정을 담당하는 update()
    public static void update(int index) {
        Student s = ArrayUtil.get(arr, index);
        
        String message;
        
        message = "새로운 국어 점수를 입력해주세요.";
        s.korean = ScannerUtil.nextInt(scanner, message, SCORE_MIN, SCORE_MAX);
        
        message = "새로운 영어 점수를 입력해주세요.";
        s.english = ScannerUtil.nextInt(scanner, message, SCORE_MIN, SCORE_MAX);

        message = "새로운 수학 점수를 입력해주세요.";
        s.math = ScannerUtil.nextInt(scanner, message, SCORE_MIN, SCORE_MAX);

        printOne(index);
    }
    
    
    //학생 정보 삭제를 담당하는 delete()
    public static void delete(int index) {
        String message = "정말로 삭제하시겠습니까? Y/N";
        String yesNo = ScannerUtil.nextLine(scanner, message);
        
        if(yesNo.equalsIgnoreCase("Y")){
            arr = ArrayUtil.remove(arr, index);
            printAll();
        }else {
            printOne(index);
        }
                
    }

}