본문 바로가기
Language/JAVA

[JAVA] 07일차. 클래스와 객체2 (1), (2)

by 전전긍긍 2022. 2. 18.

👀202202016 공부기록

 

📍본 포스팅은 인프런-Do it! 자바 프로그래밍 입문 강의를 바탕으로 작성함을 알립니다.

 

[무료] Do it! 자바 프로그래밍 입문 - 인프런 | 강의

비전공자, 문과생도 무릎을 ‘탁!’ 치며 이해하는 20년 경력 명강사의 자바 강의!, - 강의 소개 | 인프런...

www.inflearn.com


13. 클래스와 객체2 (1)

📍this

  • 자신의 메모리를 가리킴.
  • 생성자에서 다른 생성자를 호출.
  • 자신의 주소를 반환함.

1️⃣자신의 메모리를 가리킨다.

생성된 인스턴스를 스스로 가리키는 예약어.

package thisex;

//클래스
class Birthday {
	//멤버 변수
	int day;
	int month;
	int year;
	
	public void setYear(int year) {
		this.year = year;
	}
	//this가 무엇을 나타내는지 출력을 하기위해
	public void printThis() {
		System.out.println(this);
	}
}

public class ThisExample {

	public static void main(String[] args) {

		Birthday b1 = new Birthday();
		Birthday b2 = new Birthday();
		
		System.out.println(b1);
		System.out.println(b2);
		b1.printThis();
		b2.printThis();
	}

}
/*
thisex.Birthday@4517d9a3
thisex.Birthday@372f7a8d
thisex.Birthday@4517d9a3
thisex.Birthday@372f7a8d
*/

2️⃣생성자에서 다른 생성자를 호출

생성자는 객체가 생성될 때 초기화 작업을 한다. 보통 매개변수값을 세팅한다. 생성자가 한 개 이상일 경우가 있는데, 이 경우를 함수 오버로드라고 하고, 이때 생성자에서 다른 생성자를 호출할 수도 있다.

 

3️⃣자신의 주소를 반환함.

 

2️⃣&3️⃣

package thisex;

class Person {
	
	String name;
	int age;
	
	//생성자
	public Person() {
		/*this이전에 어떠한 statement도 사용할 수 없다.
		 * name = "test";*/
		//this로 다른 생성자 호출
		this("이름없음", 1);
	}
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	//자기자신 클래스 명으로 반환값을 잡음. 현재 인스턴스의 주소값
	public Person returnSelf() {
		return this;
	}
}

public class CallAnotherConst {

	public static void main(String[] args) {

		Person p1 = new Person();
		System.out.println(p1.name);
		
		System.out.println(p1.returnSelf());
	}

}

* this를 이용하여 다른 생성자를 호출할 때는 그 이전에 어떠한 statement도 사용할 수 없다. 생성자가 여러 개이고 파라미터만 다른 경우 constructor overloading 이라고 한다.


14. 클래스와 객체2 (2)

📍객체 간의 협력

 

예를 들어, 학생이 버스나 지하철을 가는 상황을 개게 지향으로 프로그래밍 하자면 다음과 같다. 객체는 학생, 버스, 지하철 3가지이다. 아래에 코드로 3개의 객체가 협력하는 것을 보여주겠다.

 

✔️버스

package cooperation;

public class Bus {
	
	int busNumber;
	int passengerCount;
	int money;
	
	public Bus(int busNumber) {
		this.busNumber = busNumber;
	}

	//승객을 태웠을 때 호출되는 메서드
	public void take(int money) {
		passengerCount++;
		this.money += money;
	}
	//버스의 정보를 보여주는 메서드
	public void showInfo() {
		System.out.println("버스 " + busNumber + "번의 승객은 " + passengerCount
				+ "명이고, 수입은 " + money + "입니다.");
	}
}

✔️지하철

package cooperation;

public class Subway {
	int lineNumber;
	int passengerCount;
	int money;
	
	public Subway(int lineNumber) {
		this.lineNumber = lineNumber;
	}

	public void take(int money) {
		passengerCount++;
		this.money += money;
	}
	
	public void showInfo() {
		System.out.println("지하철 " + lineNumber + "의 승객은 " + passengerCount
				+ "명이고, 수입은 " + money + "입니다.");
	}
}

✔️학생

package cooperation;

public class Student {
	
	String studentName;
	int grade;
	int money;
	
	public Student(String studentName, int money) {
		this.studentName = studentName;
		this.money = money;
	}
	
	//버스에 대한 정보를 매개변수로 받기
	//생성된 인스턴스가 매개변수로 들어와야 한다.
	public void takebus(Bus bus) {
		bus.take(1000);
		money -= 1000;
	}
	
	public void takeSubway(Subway subway) {
		subway.take(1500);
		money -= 1500;
	}

	public void showInfo() {
		System.out.println(studentName + "님의 남은 돈은 " + money + "이다.");
	}
}

✔️세 객체가 잘 협력하는가?