๐Ÿธ[JAVA] ์ƒ์†_(2) ๐Ÿธ

์ƒ์†๊ณผ ์ƒ์„ฑ์ž

์ƒ์„ฑ์ž๋Š” ์ƒ์† ๊ณผ์ •์—์„œ ์ƒ์„ฑ๋˜์ง€ ์•Š๊ณ , ํ•˜์œ„ ํด๋ž˜์Šค์˜ ๊ฐ์ฒด ์ƒ์„ฑ ์‹œ ์ž๋™์œผ๋กœ ์ƒ์œ„ ํด๋ž˜์Šค์˜ ์ธ์ž ์—†๋Š” ์ƒ์„ฑ์ž๊ฐ€ ํ˜ธ์ถœ๋œ๋‹ค.

  • ์ƒ์œ„ ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›๋Š” ํ•˜์œ„ ํด๋ž˜์Šค๋ฅผ ๊ฐ์ฒด ์ƒ์„ฑ ํ•  ๋•Œ ์ž๋™์œผ๋กœ ์ƒ์œ„ ํด๋ž˜์Šค์˜ ์ธ์ž ์—†๋Š” ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ƒ์†ํ•˜๋Š” ์ƒ์œ„ ํด๋ž˜์Šค์— ์ธ์ž ์—†๋Š” ์ƒ์„ฑ์ž๊ฐ€ ์—†์œผ๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒ

  • ํŠน๋ณ„ํžˆ ์ƒ์„ฑ์ž๊ฐ€ ์—†์„ ๊ฒฝ์šฐ๋Š” ๋””ํดํŠธ ์ƒ์„ฑ์ž์ธ ์ƒ์„ฑ์ž(){}์„ ์‹คํ–‰

  • ์ƒ์œ„ ํด๋ž˜์Šค์˜ ์ธ์ž์—†๋Š” ์ƒ์„ฑ์ž๋ฅผ ์ž๋™์œผ๋กœ ์‹คํ–‰ํ•˜๋ฏ€๋กœ ์ธ์ž ์—†๋Š” ์ƒ์„ฑ์ž๊ฐ€ ์—†์œผ๋ฉด ์—๋Ÿฌ ๋ฐœ์ƒ

  • ์ˆ˜์ • ๋ฐฉ๋ฒ• (ํ•˜์œ„ ํด๋ž˜์Šค์—์„œ ์ƒ์„ฑ์ž๋Š” ์ธ์ž๊ฐ’์ด ์—†์ง€๋งŒ ์ƒ์œ„ํด๋ž˜์Šค์—์„œ ์ธ์ž๊ฐ’์ด ์žˆ๋Š” ๊ฒฝ์šฐ )

    (1) ์ƒ์œ„ ํด๋ž˜์Šค์— ์ƒ์„ฑ์ž ( ){ }์„ ์ถ”๊ฐ€ํ•œ๋‹ค.
    (2) ํ•˜์œ„ ํด๋ž˜์Šค์—์„œ super( ) ๋ฉ”์†Œ๋“œ ์ด์šฉํ•ด์„œ ํ˜ธ์ถœ

    class Greeting {
    	public String name = "๊น€์œ ์ง„";
    	public int age = 18;
    	public void sayHello() {
    		System.out.println("์”จ ์•ˆ๋…•ํ•˜์„ธ์š”.");
    	}
    }
    class EngHello extends Greeting{
    	public String name = "Mr.hee";
    	public int age = 18;
    	public void sayHello() {
    		System.out.println(age + "์‚ด์˜ "+name+" Nice to meet you");
    	}
    	public void test() {
    		System.out.print(super.age + "์‚ด์˜ "+ super.name);
    		super.sayHello();
    	}
    	public static void main(String args[]) {
    		EngHello eng = new EngHello();
    		eng.sayHello();
    		eng.test();
    	}
    }

superํ‚ค์›Œ๋“œ์™€ super()๋ฉ”์„œ๋“œ

์ƒ์†๊ด€๊ณ„์— ์žˆ๋Š” ํด๋ž˜์Šค์—์„œ ์ƒ์œ„ ํด๋ž˜์Šค์˜ ๋ฉค๋ฒ„๋ณ€์ˆ˜๋‚˜ ์ƒ์„ฑ์ž๋ฅผ ํ˜ธ์ถœํ•˜๊ธฐ ์œ„ํ•ด superํ‚ค์›Œ๋“œ super()๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

(๊ฐ€) superํ‚ค์›Œ๋“œ

์ƒ์œ„ ํด๋ž˜์Šค์˜ ๋ฉค๋ฒ„ ๋ณ€์ˆ˜๋‚˜ ๋ฉ”์†Œ๋“œ๋ฅผ ํ•˜์œ„ ํด๋ž˜์Šค์—์„œ ๋ช…์‹œ์ ์œผ๋กœ ํ˜ธ์ถœํ•  ๋•Œ ์‚ฌ์šฉ

ํ˜•์‹
(1) super. ์ƒ์œ„ ํด๋ž˜์Šค์˜ ๋ฉค๋ฒ„๋ณ€์ˆ˜
(2) super. ์ƒ์œ„ ํด๋ž˜์Šค์˜ ๋ฉ”์†Œ๋“œ์ด๋ฆ„

(๋‚˜) super()๋ฉ”์†Œ๋“œ

์ƒ์œ„ ํด๋ž˜์Šค์˜ ์ƒ์„ฑ์ž๋ฅผ ๋ช…์‹œ์ ์œผ๋กœ ํ˜ธ์ถœํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์œผ๋กœ ํ•˜์œ„ ํด๋ž˜์Šค์˜ ์ƒ์„ฑ์ž์—์„œ ์ œ์ผ ๋จผ์ € ํ˜ธ์ถœํ•ด์•ผ ํ•œ๋‹ค.

ํ˜•์‹
(1) super( )
(2) super(์ธ์ž...)

class Grandfather {
	private String name;
	private int age;
	public Grandfather(String name,int age) {
		this.name = name;
		this.age = age;
		System.out.println("Grandfather ์ƒ์„ฑ์ž"+" "+this.name +" "+this.age+"์‚ด์ด๋‹ค.");
	}
}
class Myclass extends Grandfather{
	
	public Myclass(String str,int age) {
		super(str, age);
		System.out.println("MyClass ์ƒ์„ฑ์ž");
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Myclass s = new Myclass("๊น€์œ ์ง„",18);
	}

}

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ