Java

์ž๋ฐ”์˜ ์ƒ์†์ž์— ๋Œ€ํ•ด ํ•™์Šตํ•˜๊ธฐ

567Rabbit 2024. 6. 3. 10:11

 

 

public class Child extends Parent ํ•˜๋ฉด Parent๋ฅผ Child ํด๋ž˜์Šค์— ์ƒ์†๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

 

 

 

child๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ์ด๋ฆ„, ๋‚˜์ด, ์žฌ์‚ฐ์— ๊ด€ํ•œ ๋ถ€๋ถ„์€ Parent์— ์žˆ์–ด์„œ name,age,money ๋ถ€๋ถ„์— ๋นจ๊ฐ„ ๋ฐ‘์ค„์ด ์ƒ๊ธด๋‹ค.

package model;

public class Child extends Parent {
	
	private String hobby;

	public String getHobby() {
		return hobby;
	}

	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	
	public void printChild(){
		System.out.println("์ด๋ฆ„ : "+name+", ๋‚˜์ด : "+age+", ์žฌ์‚ฐ : "+money+", ์ทจ๋ฏธ : "+hobby);
	}
	

}

 

 

 

Parent์˜ ๋ณ€์ˆ˜์—์„œ, private์ด ์•„๋‹Œ protected๋กœ ๋ฐ”๊ฟ”์ฃผ๋ฉด ์ƒ์†๊ด€๊ณ„์—์„œ ์ž์œ ๋กญ๊ฒŒ ๋ณ€์ˆ˜ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

	protected String name; //์ƒ์†๊ด€๊ณ„์—์„œ๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ protected
	protected int age;
	protected int money;

 

 

 

Main์— ์™€์„œ ์•„๋ž˜์™€ ๊ฐ™์ด ์ž…๋ ฅํ•ด์ฃผ๋ฉด,

    Child c = new Child();
    c.setName("ํ™๋‚˜๋‚˜");
    c.setAge(25);
    c.setMoney(1000000);
    c.setHobby("๊ฒŒ์ž„");

    c.printChild();

 

 

 

 

์ด์ฒ˜๋Ÿผ ์ƒ์†๋œ ๋‚ด์šฉ์„ ๊ฐ™์ด ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ๋‹ค.