๐ฃ์ํ์ฝ๋ฉ ๊ฐ์๐ฃ
Java ์์
https://www.youtube.com/playlist?list=PLuHgQVnccGMA1bRSk_SZrXMngx5iq03cc
- ๊ณ์ฐ๊ธฐ ์์
→ ๋ถ๋ชจ ํด๋์ค : Cal
→ ์์ ํด๋์ค : Cal2
Extends, Overriding, Overloading, Super ์ฌ์ฉํ๊ธฐ
class Cal {
public int sum(int v1, int v2) {
return v1 + v2;
}
// overloading (์์๊ณผ ๊ด๋ จ๋ ๊ฒ์ ์๋)
public int sum(int v1, int v2, int v3) {
// return v1 + v2 + v3; ๊ณผ ๊ฐ์ ํจ๊ณผ
// this ๋ ์๊ธฐ ์์ ์ ๊ฐ๋ฆฌํด
return this.sum(v1, v2) + v3;
}
}
class Cal2 extends Cal {
// overriding : ๋ถ๋ชจ๊ฐ ๊ฐ์ง ๊ธฐ๋ฅ์ ์ฌ์ ์ (๋ฎ์ด์ฐ๊ธฐ)
public int sum(int v1, int v2) {
System.out.println("Cal2!!");
// return v1 + v2; ๊ณผ ๊ฐ์ ํจ๊ณผ
// ๋ถ๋ชจ ํด๋์ค์ sum ์ ๊ฐ๋ฆฌํค๊ฒ ๋จ
return super.sum(v1,v2);
}
public int minus(int v1, int v2) {
return v1 - v2;
}
}
public class Main {
public static void main(String[] args) {
Cal c = new Cal();
System.out.println(c.sum(2,1));
System.out.println(c.sum(1,2,3));
Cal2 c2 = new Cal2();
System.out.println(c2.sum(2,1));
System.out.println(c2.minus(2,1));
}
}
· Extends
class Cal2 extends Cal { ... }
โก๏ธ Cal2 ํด๋์ค๊ฐ Cal ํด๋์ค๋ฅผ ํ์ฅ์ํจ๋ค (์์๋ฐ๋๋ค)
· Overriding
class Cal {
public int sum(..) {..}
}
class Cal2 extends Cal {
public int sum(..) {..}
}
โก๏ธ ๋ถ๋ชจ ํด๋์ค์ธ Cal ์ด ๊ฐ์ง sum ๋ฉ์๋๋ฅผ ์์ ํด๋์ค์ธ Cal2 ์์ ๋ค์ ์ ์ํ๋ค
· Overloading
class Cal {
public int sum(int v1, int v2) { return v1 + v2; }
public int sum(int v1, int v2, int v3) { return v1 + v2 + v3; }
}
โก๏ธ ํ ํด๋์ค ๋ด์์ ์ด๋ฆ์ด ๊ฐ์ sum ๋ฉ์๋๋ฅผ ๋ค๋ฅธ ๋งค๊ฐ๋ณ์ ํ์ ํน์ ๊ฐ์๋ก ์ ์ํ๋ค
· Super
class Cal2 extends Cal {
public int sum(..) { return super.sum(v1,v2); }
}
โก๏ธ ์์ ํด๋์ค์ธ Cal2 ์์ ๋ถ๋ชจ ํด๋์ค์ธ Cal ์ sum ๋ฉ์๋๋ฅผ ํธ์ถํ๊ฒ ๋๋ค
์์ฑ์, this ์ฌ์ฉํ๊ธฐ
class Cal {
int v1, v2;
Cal(int v1, int v2) { // ์์ฑ์
System.out.println("Cal init!!");
this.v1 = v1;
this.v2 = v2;
}
// this : ์๊ธฐ ์์ ๊ฐ๋ฆฌํค๊ธฐ
public int sum() {return this.v1+v2;}
}
class Cal2 extends Cal {
Cal2(int v1, int v2) {
super(v1, v2); // ๋ถ๋ชจ ํด๋์ค์ ์์ฑ์ ํธ์ถ
System.out.println("Cal2 init!!");
}
public int minus() {return this.v1-v2;}
}
public class Main {
public static void main(String[] args){
Cal c = new Cal(2,1);
Cal2 c2 = new Cal2(2,1);
System.out.println(c2.sum()); // 2
System.out.println(c2.minus()); // 1
}
}
'Spring > JAVA' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Java ์ ์ด๋ฌธ1 - Boolean, ๋น๊ต&๋ ผ๋ฆฌ ์ฐ์ฐ์ (0) | 2023.10.04 |
---|---|
Java Interface (0) | 2023.10.03 |
Java ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ (2) | 2023.09.29 |
Java Method (0) | 2023.09.28 |
Java ์์ธ (Try-Catch / Try-Catch-Finally / Try with Resource Statements / Throws) (0) | 2023.09.26 |