본문 바로가기
Java/[패스트캠퍼스] Java & SpringBoot로 시작하는 웹 프로그래밍

Ch 02. 객체 지향 입문 - 04. 객체의 속성은 멤버 변수로, 객체의 기능은 메서드로 구현한다

by hinote 2022. 12. 30.

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

  • 학생 클래스의 속성을 멤버 변수로 선언하고 메서드를 구현한다
public class Student {
	
	public int studentID;
	public String studentName;  
	public String address;
    	//이렇게 세 개의 속성을 가지고 있다
			
	public void showStudentInfo() { //학생의 정보를 보여주는 메서드 만들기
		System.out.println(studentID + "학번 학생의 이름은 " + studentName + "," + address);
        			//반환값이 없으니 바로 출력하여 보이도록 함
	}
	
	public String getStudentName() { //studentName을 가져가는 함수 만들기  
    			//(이름을 지정하거나 반환하는 메서드 만들어야 하기 때문에)
		return studentName; //studentName 변수값을 반환함
	}
    
    public String setStudentName(String name) {
    //어떤 이름으로 지정해야겠다, 바꾸겠다 할 때 반환값은 없다.
    //이름을 셋팅하기 때문에 set을 붙이고, 어떤 이름으로 바꿀건지 매개변수가 들어가야 함
	studentName = name;
}

 

 

 

 

 

  • 학생 클래스를 생성하여 생성된 객체(인스턴스)에 각각 다른 이름과 주소를 대입한다

 

인스턴스는 생성자로 호출해서 만들 수 있음
클래스가 있으면 클래스 기반으로 여러 인스턴스가 생길 수 있음

 

 

public class StudentTest {

	public static void main(String[] args) {
		
		Student studentLee = new Student();
        	//데이터타입 변수이름 = new키워드 생성자 =>학생 하나를 생성해라
		studentLee.studentID; = 12345;
		studentLee.setStudentName("Lee");        
//		studentLee.studentName = "이순신"; 위와 같이 이용 가능
		studentLee.address = "서울";
		
		
		studentLee.showStudentInfo(); //학생 정보를 보여주는 메서드를 만들었었음
		
		Student studentKim = new Student(); //새로운 학생 하나를 더 입력함
		studentKim.studentID; = 54321;	
		studentKim.studentName = "김유신";
		studentKim.address = "경주";
		
		studentKim.showStudentInfo();
		
		System.out.println(studentLee);
		System.out.println(studentKim);
	}

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

댓글