클래스(Class)

로로·2023년 8월 6일

클래스(Class)

  • 객체에 대한 속성기능을 코드로 구현한 것
  • 객체에 대한 청사진
  • 속성 : 객체의 특성, 속성, 멤버 변수, property, attribute
    기능 : 메서드, 멤버 함수

🔵 기본

(접근제어자) class 클래스명 {
    멤버변수;
    메서드;
}
  • 클래스명 : 대문자로 시작하며, 파일명과 같아야함
  • 클래스 파일 1개 에는 여러 class가 들어갈 수 있지만, public은 1개만 포함할 수 있음

🔵 클래스 정의

public class Student {
    // 속성 : 멤버 변수
    int studentId;
    String studentName;
    int grade;
    String address;
    
    // 기능 : 메서드
    public void showStudentIdAndStudentName(){
        System.out.println(studentId);
        System.out.println(studentName);
    }
    
    public String getStudentName(){
        return studentName;
    }

    public void setStudentName(String name){
        studentName = name;
    }
}
  • 속성 : 학번, 이름, 학년 사는 곳 등등
  • 기능 : 수강신청, 수업듣기, 등등

🔵 클래스 사용

public static void main(String[] args){
        // class 생성 (instance)
        Student student1 = new Student();

        // 값 할당
        student1.studentId = 1;
        student1.studentName = "이순신";

        // 메서드 사용
        student1.showStudentIdAndStudentName();

        System.out.println(student1.getStudentName());

        student1.setStudentName("홍길동");
        student1.showStudentIdAndStudentName();

        // 힙 메모리에 생성된 인스턴스의 주소값 출력
        System.out.println(student1);
    }

함수 vs 메서드

메서드는 클래스 내 멤버변수로 구현된 함수

함수

🔵 기본

함수반환타입 함수명 (매개변수타입 매개변수, ...){
    ...
    return ___ ;
}

🔵 예제

public class FunctionTest {

    public static void main(String[] args){
        int num1 = 10;
        int num2 = 20;

        int result = add(num1, num2);
        System.out.println(result);

    }
    public static int add (int x, int y){
        int result;
        result = x + y;
        return result;
    }
}

class & instance

클래스(static 코드) - 생성(인스턴스화) -> 인스턴스(dynamic memory)

🔵 기본

클래스 변수이름 = new 생성자;
  • class : Dog
  • instance : 아또, 두리, 등등

🔵 예제

Dog duri = new Dog();
  • 기본 데이터타입 : int, String
  • 참조형 데이터타입 : Dog
  • 참조 변수 : 변수명, duri

생성자(constructor)

  • 인스턴스를 초기화할 때 명령어의 집합
  • 생성자명 = 클래스명
  • 생성자는 new 키워드로 호출될때만 사용
  • 메소드가 아니라서 상속 X, 리턴값 X
  • 기본 생성자 : jvm(컴파일러)이 디폴트로 만들어줌! 매개변수X, 함수내용X
  • 생성자 오버로딩 : 기본 생성자가 아닌 생성자를 추가하면, 컴파일러가 디폴트로 추가해주지 않음
public class Student {

	// 기본 생성자
    // 따로 정의하지 않아도 jvm이 디폴트로 자동 생성
	public Student(){
    }
    
    // 정의한 생성자
    // 기본 생성자를 따로 정의하지 않은 경우, 매개 변수를 포함하여 생성해야 함
    public Student(int id, String name){
        studentId = id;
        studentName = name;
    }
    
    // => 기본 생성자와 함께 정의한 경우, 둘다 사용 가능
profile
청로하~🏝️

0개의 댓글