학생 클래스를 정의 하고 이를 사용 해보자.

package ch04

public class Student {

public int studentID;
public String studentName;
public String address;

public void showStudentInfo(){ 
   System.out.println( studentID + "학번 학생의 이름은 " + studentName + " 이고, 주소는 " + address + "입니다. ");
 }
 //학생 이름을 지정 하거나 반환하는 메서드를 만들어 보자.
 //반환값은 String으로..
 public String getStudentName() {
 return studentName;
  }
 public void setStudentName(String name) {
    studentName = name;
  }
  
}

클래스를 이대로 만들어 보고, 클래스를 쓰는 클래스를 따로 만들어 보자.

StudentTest라는 클래스를 만들어보자.

package ch04;

public class StudentTest {
  public static void main(String[] args) {
    //데이터 타입을 클래스를 가져다 쓸 경우, 크기가 정해져 있는 것은 아니다.
    Student studentLee = new Student();
    //클래스가 있으면 클래스를 기반으로 여러개의 인스턴스 변수가 생성 될 수 있다.
    
    studentLee.studentID = 12345;
    studentLee.setStudentName("Lee");
    studentLee.address = "서울 강남구";
    
    studentLee.showStudentInfo(); //12345학번 학생의 이름은 Lee이고, 주소는 서울 강남구 입니다.
    
    Student studentKim = new Student();
    studentKim.studentID = 54321;
    studentKim.studentNam = "Kim";
    studentKim.address = "경기도 성남시";
    
    studentKim.showStudentInfo(); //54321학번 학생의 이름은 Kim이고, 주소는 경기도 성남시입니다.
    
    
  }
}

인스턴스는 생성자는 new를 통해 만들 수가 있고,

인스턴스가 생성이 되는 곳을 Heap memory이고, 지역변수는 Stack memory이다.

다음 시간에는 Heap memory가 어떻게 관리 되는지 알아보자.

 

 

참고: FastCampus

 

+ Recent posts