๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java

[Java] ๊ฐ์ฒด ๊ฐ„ ํ˜‘๋ ฅ

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 2. 18.
๋ฐ˜์‘ํ˜•

โ–ถ ๊ฐ์ฒด ๊ฐ„ ํ˜‘๋ ฅ

package cooperation;

public class Student {
	public String studentName; // ํ•™์ƒ ์ด๋ฆ„
	public int grade; // ํ•™๋…„
	public int money; // ํ•™์ƒ์ด ๊ฐ€์ง€๊ณ  ์žˆ๋Š” ๋ˆ

	public Student(String studentName, int money) {  // ์ด๋ฆ„๊ณผ ๋ˆ ์ดˆ๊ธฐํ™”ํ•˜๊ธฐ
		this.studentName = studentName;
		this.money = money;
	}

	public void takeBus(Bus bus) {
		bus.take(1000);
		this.money -= 1000;
	}

	public void takeSubway(Subway subway) {
		subway.take(1500);
		this.money -= 1500;
	}

	public void showInfo() {
		System.out.println(studentName + "๋‹˜์˜ ๋‚จ์€ ๋ˆ์€ " + money + "์ž…๋‹ˆ๋‹ค.");
	}

}
package cooperation;

public class Bus {
	int busNumber;  // ๋ฒ„์Šค ๋ฒˆํ˜ธ
	int passengerCount;  // ์Šน๊ฐ ์ˆ˜
	int money;  // ๋ฒ„์Šค์˜ ์ˆ˜์ž…

	public Bus(int busNumebr) {  // ๋ฒ„์Šค ๋ฒˆํ˜ธ๋ฅผ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๋ฐ›๋Š” ์ƒ์„ฑ์ž
		this.busNumber = busNumebr;
	}

	public void take(int money) {  // ์Šน๊ฐ์ด ๋‚ธ ๋ˆ์„ ๋ฐ›์Œ
		this.money += money;  // ๋ฒ„์Šค์˜ ์ˆ˜์ž… ์ฆ๊ฐ€
		passengerCount++;  // ์Šน๊ฐ ์ˆ˜ ์ฆ๊ฐ€
	}

	public void showInfo() {  // ๋ฒ„์Šค ์ •๋ณด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ•จ์ˆ˜
		System.out.println("๋ฒ„์Šค " + busNumber + "๋ฒˆ์˜ ์Šน๊ฐ์€ " + passengerCount + "๋ช…์ด๊ณ , ์ˆ˜์ž…์€ " + money + "์ž…๋‹ˆ๋‹ค.");
	}

}
package cooperation;

public class Subway {
	public String lineNumber;  // ์ง€ํ•˜์ฒ  ๋…ธ์„  ๋ฒˆํ˜ธ
	public int passengerCount;  // ์Šน๊ฐ ์ˆ˜
	public int money;  // ์ˆ˜์ž… ์•ก

	public Subway(String lineNumber) {  // ์ง€ํ•˜์ฒ  ๋…ธ์„  ์ดˆ๊ธฐํ™”
		this.lineNumber = lineNumber;
	}

	public void take(int money) {  // ์Šน๊ฐ์ด ํƒ„ ๊ฒฝ์šฐ
		this.money += money;  // ์ˆ˜์ž… ์ฆ๊ฐ€
		passengerCount++;  // ์Šน๊ฐ ์ˆ˜ ์ฆ๊ฐ€
	}

	public void showInfo() {  // ์ง€ํ•˜์ฒ  ์ •๋ณด ์ถœ๋ ฅ
		System.out.println(lineNumber + "์˜ ์Šน๊ฐ์€ " + passengerCount + "๋ช…์ด๊ณ , ์ˆ˜์ž…์€ " + money + "์ž…๋‹ˆ๋‹ค.");
	}

} 
package cooperation;

public class TakeTrans {
	public static void main(String[] args) {

		Student studentJames = new Student("James", 5000);
		Student studentTomas = new Student("Tomas", 10000);

		Bus bus100 = new Bus(100);
		studentJames.takeBus(bus100);  // james๊ฐ€ 100๋ฒˆ ๋ฒ„์Šค๋ฅผ ํƒ
		studentJames.showInfo();  // james ์ •๋ณด ์ถœ๋ ฅ
		bus100.showInfo();  // ๋ฒ„์Šค ์ •๋ณด ์ถœ๋ ฅ

		Subway subwayGreen = new Subway("2ํ˜ธ์„ ");
		studentTomas.takeSubway(subwayGreen);  // Tomas๊ฐ€ 2ํ˜ธ์„ ์„ ํƒ
		studentTomas.showInfo();  // Tomas ์ •๋ณด ์ถœ๋ ฅ
		subwayGreen.showInfo();

	}
}

<๊ฒฐ๊ณผ๊ฐ’>

 

๋ฐ˜์‘ํ˜•

'Java' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Java] ํด๋ž˜์Šค ๋ฉ”์„œ๋“œ  (0) 2021.02.18
[Java] Static ๋ณ€์ˆ˜  (0) 2021.02.18
[Java] this ์˜ˆ์•ฝ์–ด  (0) 2021.02.18
[Java] ์—ฐ์Šต๋ฌธ์ œ + ์‹ค์Šต  (0) 2021.02.18
[Java] ์ •๋ณด ์€๋‹‰  (0) 2021.02.18

๋Œ“๊ธ€