객체 지향 프로그래밍

doremi·2025년 2월 5일

Java

목록 보기
6/10
post-thumbnail

1️⃣Student 클래스와 2️⃣StudentMain 클래스의 연관성

  • StudentMain 클래스는 Student 클래스를 이용해서 객체를 생성하고, 메서드를 호출하여 조작하는 실행 클래스

1️⃣ Student 클래스 (설계도 역할)

  • Student 클래스는 학생의 정보(이름, 점수 등)를 저장하고, 조작할 수 있는 기능(메서드)
  • 학생 한 명 한 명을 객체로 만들어서 사용할 수 있도록 하는 설계도
package ch09_class.students;

import ch09_class.students.util.UtilClass;

public class Student {

	
	//1. 필드, 속성값
	// public: 공개, 프로젝트 어디서든 사용가능
	//private : 비공개, 현재 클래스 내에서만 접근
	private String name;
	private int kor;
	private int eng;
	private int math;
	private double avg;
	//2. 생성자 (class는 생성자를 정의하지 않아도 무조건 클래스명의 생성자가 있음.)
	// 단축키 shift + alt + s
	
	public Student(String name) {
		this.name = name;
		save();   //(name + "등록됨");
	}

	public Student(String name, int kor, int eng, int math) {
		this.name = name;
		this.kor = kor;
		this.eng = eng;
		this.math = math;
	}

	public Student() {
	}
	//3. toString 출력

	@Override
	public String toString() {
		return "Student [name=" + name + ", kor=" + kor + ", eng=" + eng + ", math=" + math + ", avg=" + avg + "]";
	}
	//4.getter, setter     //✅값을 변경하는 메소드 (Setter),  ✅값을 가져오는 메소드 (Getter)


	public String getName() {          
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getKor() {
		return kor;
	}

	public void setKor(int kor) {
		this.kor = kor;
		setAvg();  //점수 변경이 일어나면 평균계산
	}

	public int getEng() {
		return eng;
	}

	public void setEng(int eng) {
		this.eng = eng;
		setAvg();  //점수 변경이 일어나면 평균계산
	}

	public int getMath() {
		return math;
	}

	public void setMath(int math) {
		this.math = math;
		setAvg();  //점수 변경이 일어나면 평균계산
	}

	private void setAvg() {
		// this.kor 동일함
		this.avg = util.UtilClass.weRound((kor + eng + math) / 3.0, 2);
	}

	public void nm() {
		System.out.println(name + " 입니다.");
	}

	private void save() {
		System.out.println(name + "등록됨");
	}

	public static void check() {
		System.out.println("student의 static method 클래스명.check로 호출가능");
	}
	
	
	
}

💡 정리
✅ 학생의 이름과 점수를 저장하고 관리
✅ 점수를 변경하면 자동으로 평균을 다시 계산
✅ 학생 정보를 toString() 메서드로 출력 가능
static 메서드를 활용하여 공용 기능 제공 (check() 메서드)


2️⃣ StudentMain 클래스 (실제 사용)

  • Student 클래스를 실행하는 메인 클래스에서 Student 객체를 생성하고, 다양한 메서드를 호출
package ch09_class.students;

import java.util.ArrayList;

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

		
		Student stu1 = new Student("팽수"); //new 클래스를 사용하기 위해 인스턴스화  
		Student stu2 = new Student("팽순"); //new 클래스를 사용하기 위해 인스턴스화   
		Student stu = new Student();    								 
		
		System.out.println(stu1);   
		
		System.out.println(stu1.getName());   
		
		stu1.setName("김토리");					
		System.out.println(stu1.getName());    
		
		System.out.println(stu2.getName());    

	stu1.setKor(90);
	System.out.println(stu1);    

	stu1.setMath(75);
	System.out.println(stu1);   

	stu1.nm();   // 김토리입니다.
	
	Student.check(); //정적메소드 호출   // ✅static(=정적) 메소드
	
//	Student.nm();  //class의 기본 메소드는 인스턴스 메소드임(인스턴스화 이후 사용가능)
	
	ArrayList<Student> classMate =  new ArrayList<Student>();
	classMate.add(stu1);
	classMate.add(stu2);
	for (Student st : classMate) {
		System.out.println(st.getName());    // 김토리, 팽순
	}
	
	
	}
}

💡 정리
StudentMain에서 Student 객체를 생성 (new Student("팽수"))
setKor(), setMath() 등을 이용해 점수를 변경하면 자동으로 평균이 계산됨
ArrayList<Student>를 이용해 여러 학생을 저장하고 관리할 수 있음
📖 Student.check(); 같은 static 메서드는 객체 생성 없이도 호출 가능
(밑에 설명있음)


🌈 결론

✔️ Student 클래스는 "학생" 객체를 다룰 수 있는 설계도
✔️ StudentMain 클래스는 Student 객체를 생성하고 실제로 사용하는 실행 코드


📌 사용 관계

  • StudentMain 클래스가 Student 클래스를 직접 사용
  • StudentMainStudent 객체를 생성하고, 그 객체의 메서드(setKor(), getName() 등)를 호출
    • StudentMain이 "Student를 사용한다."
    • 한 클래스(StudentMain)가 다른 클래스(Student)를 필요로 하고, 객체를 생성해서 사용하는 관계

✍️ 예시

Student stu1 = new Student("팽수"); // Student 객체 생성 (사용)
System.out.println(stu1.getName()); // Student 객체의 메서드 사용

📌 집합 관계

  • StudentMain 클래스 안에서 ArrayList<Student>를 사용해서 여러 개의 Student 객체를 모아 관리
  • 하나의 객체(StudentMain)가 여러 개의 객체(Student)를 포함하는 구조
    • "반(클래스)에는 여러 학생이 있다."
    • StudentMainStudent 객체들을 소유하지만, 독립적으로 존재할 수 있음.

✍️ 예시

ArrayList<Student> classMate = new ArrayList<>(); // 여러 학생을 담을 리스트
classMate.add(stu1);
classMate.add(stu2);

💡 정리
StudentMainStudent = 사용 관계
StudentMainArrayList<Student>로 여러 학생 관리 = 집합 관계


📖 Student.check();

  • static 키워드가 붙은 메소드로, 클래스 자체에 속하는 메소드
    객체를 만들지 않아도 클래스명.메소드명() 형식으로 바로 호출

📌 Student 클래스에서의 static 메소드 예시

  public class Student {
    public static void check() {  // static 메소드
        System.out.println("student의 static method 클래스명.check로 호출가능");
    }
}

📌 객체 없이 직접 호출 가능

Student.check();  // student의 static method 클래스명.check로 호출가능

➡️ Student 클래스의 객체(new Student())를 만들지 않고도 바로 호출 가능!

✍️ 예시

Student stu1 = new Student();
stu1.nm();  // ✅ 객체가 있어야 호출 가능

Student.check();  // ✅ 객체 없이 바로 호출 가능

📌 정적 메소드는 언제 사용?

  • 객체 없이도 공통적으로 사용할 기능이 있을 때!
  • 공통적인 메시지 출력 (check() 처럼)

💡 정리

Student.check();는 객체를 생성하지 않고, Student 클래스 자체에서 호출
static 메소드는 클래스명으로 직접 호출 가능 (클래스명.메소드명())
✅ 인스턴스 메소드와 달리 객체 없이도 동작

profile
🌈오늘의 공부는 여기까지! ᕦ(ò_óˇ)ᕤ

0개의 댓글