클래스를 정의 하고 이를 사용해보자
학생의 클래스를 정의
학생 클래스의 멤버 변수(학생의 속성)를 선언하고 메서드(객체의 기능)를 구현한다.
package ch04;
public class Student {
public int studentID; //변수(속성) 선언
public String studentName;
public String address;
public void showStudentInfo (){ //showStudentInfo 가 메서드
System.out.println(studentID + "학번 학생의 이름은"+ "studentName" +"이고,주소는"+address+"입니다.");
}
public String getStudentName() { //studentName를 반환하는 메서드
return studentName;
}
public void setStudenteName(String name) { //이름을 변경하는 메서드 name는 매개변수
studentName = name;
}
}
위와같이 학생의 클래스를 생성하고 생성된 객체(인스턴스)에 각각의 다른 이름과 주소를 대입한다.
(인스턴스 - 클래스를 통해 생성자를 사용하여 생성된 객체 )
package ch04;
public class StudentTest {
public static void main(String[] args) {
Student studentLee = new Student();
// studentLee가 인스턴스임
studentLee.studentID = 12345;
studentLee.setStudenteName("lee");
studentLee.address = "서울 강남구";
studentLee.showStudentInfo();
Student studentKim = new Student();
studentKim.studentID = 54321;
studentKim.studentName = ("kim");
studentKim.address = "경기도 성남시";
studentKim.showStudentInfo();
}
}
생성자 (0) | 2022.07.12 |
---|---|
인스턴스 생성과 힙 메모리 (0) | 2022.07.11 |
함수와 메서드 (0) | 2022.07.11 |
생활 속에서 객체를 찾아 클래스로 구현해보기 (0) | 2022.07.08 |
객체와 객체 지향 프로그래밍 (0) | 2022.07.08 |