Spring/JAVA

Java ์ƒ์†

alsruds 2023. 10. 2. 23:21
๐Ÿฃ์ƒํ™œ์ฝ”๋”ฉ ๊ฐ•์˜๐Ÿฃ

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
    }
}

์ถœ๋ ฅ ๊ฒฐ๊ณผ