Backend/JAVA

JAVA 클래스 인스턴스 예제

heeju 2023. 7. 4. 16:09

 

객체 : 객체 지향 프로그램의 대상, 생성된 인스턴스
클래스 : 객체를 프로그래밍 하기위해 코드로 정의해 놓은 상태  (설계도 역할)
인스턴스 : new 키워드를 사용하여 클래스를 메모리에 생성한 상태  (설계도를 실제 사용) 

                 - 클래스 기반으로 여러개의 인스턴스 생성이 가능

                 - new 키워드로 인스턴스를 생성할때 메모리 할당을 함 = 동적 메모리(heep memory)
멤버 변수 : 클래스의 속성, 특성
메서드 : 멤버 변수를 이용하여 클래스의 기능을 구현한 함수 (객체의 기능)
참조 변수 : 메모리에 생성된 인스턴스를 가리키는 변수
참조 값 : 생성된 인스턴스의 메모리 주소 값

 

 

 

Student.java

public class Student {

    // 멤버 변수
    int studentID;
    String studentName;
    String address;

    // 메서드
    public int getStudentID() { // studentID를 불러오는 메서드
        return studentID;
    }

    public void setStudentID(int studentID) { // studentID의 값을 지정하는 메서드
        // this는 이 클래스(Student)를 가리킴 = 이 클래스의 멤버변수가 this.studentID
        this.studentID = studentID; // 멤버변수에 매개변수 대입
    }

    public String getStudentName() { // studentName를 불러오는 메서드
        return studentName;
    }

    public void setStudentName(String studentName) { // studentName의 값을 지정하는 메서드
        this.studentName = studentName;
    }

    public void showStudentInfo() { // console에 출력하는 메서드
        System.out.println(studentID + "학번, 이름 " + studentName + ", 주소 " + address);
    }

}

 

 

StudentTest.java

public class StudentTest {

    public static void main(String[] args) {

        // Student 타입 지정
        // studentLee, studentKim = 참조변수 (생성되는 클래스의 메모리의 위치를 나타냄)
        Student studentLee = new Student(); // 인스턴스 생성

        studentLee.setStudentID(12345);
        studentLee.setStudentName("Lee");
        studentLee.address = "서울 마포구";

        studentLee.showStudentInfo(); // 결과 : 12345학번, 이름 Lee, 주소 서울 마포구

        Student studentKim = new Student();

        studentKim.setStudentID(54321);
        studentKim.studentName = "Kim";
        studentKim.address = "서울시 동작구";

        studentKim.showStudentInfo(); // 결과 : 54321학번, 이름 Kim, 주소 서울시 동작구
        
        // JVM이 준 가상 주소가 나타남 (참조값)
        System.out.println(studentLee); 
        System.out.println(studentKim);
    }

}

 

 

 

 

반응형