Java 기초-02

wonder1ng·2025년 4월 1일

풀스택 기초

목록 보기
12/13

03 조건문

  • if: 조건 판별
  • else if: 나머지 조건 판별
  • else: 나머지 실행
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        // 조건문
        // * 자바스크립트 문법과 거의 동일
        // 1. 단일 if문
        // 패턴
        // if (조건절-비교,논리 연산자) {
        //    true일 때 수행문
        // }
        if (10 < 20) {
            System.out.println("10이 20보다 작음");
        }
        // 실행문이 한 줄일 때 중괄호 생략 가능
        if (10 < 20) System.out.println("10이 20보다 작음");

        // 2. if else문
        if (10 > 20) {
            System.out.println("10 > 20");
        } else System.out.println("10 <= 20");

        // 3, if else if문
        int score = 80;
        if (score == 90) {
            System.out.println("90");
        } else if (score == 80) {
            System.out.println("80");
        } else {
            System.out.println("그외의 수");
        }
        //4. 중첩 if문
        if (true) { //조건1
            if (false) { //조건2
                //조건1이고(AND) 조건2이다.
            } else if (true) { //조건3
                //조건1이고 조건2는 아니고, 조건 3이다.
            }
        }
        //자바에서 랜덤수 발생
        //1. Math.random()  0.0 ~ 0.99999...
        //2. Random 클래스
        //   rand.netxInt(6) 0 ~ 5 까지의 랜덤 정수 발생

        for (int i = 1; i <= 6; i++) {
            for (int j = 1; j <= 6; j++) {
                System.out.println("i,j:" + i + "," + j);
            }
        }


        //연습문제
        //1.
        //철수와 영희가 주사위 놀이를 하고 있다.
        // 주사위 2개를 던져서,
        // 두개 다 짝수가 나오면 철수 승!
        // 두개 다 홀수가 나오면, 영희 승!
        // 그외의 경우는 무승부! 이다.
        // 게임의 결과를 출력하시오.
        Random rand = new Random();
        int dice1 = rand.nextInt(6) + 1;
        int dice2 = rand.nextInt(6) + 1;
        System.out.println(dice1);
        System.out.println(dice2);
        if (dice1 % 2 == 0 && dice2 % 2 == 0) {
            System.out.println("철수 승!");
        } else if (dice1 % 2 == 1 && dice2 % 2 == 1) {
            System.out.println("영희 승!");
        } else {
            System.out.println("무승부!");
        }
        System.out.println();
        //2.
        //철수와 영희을 주사위게임을 하고 있다.
        //주사위 2개를 철수가 던지고,
        //주사위 2개를 영희도 던진다.
        //게임룰 : 첫번째 주사위는 십의 자릿수로하고,
        //        두번째 주사위는 일의 자릿수로 해서,
        // 더 높은 점수를 가진 사람이 승리한다.
        //출력값 예시 :
        //        철수 주사위1 수 : 1
        //        철수 주사위2 수 : 3
        //        철수의 점수는 13
        //        영희 주사위1 수 : 3
        //        영희 주사위2 수 : 4
        //        영희의 점수는 34
        //        영희 승!
        int fir = Integer.parseInt(Integer.toString(rand.nextInt(6)) + rand.nextInt(6)) + 11;
        int sec = Integer.parseInt(Integer.toString(rand.nextInt(6)) + rand.nextInt(6)) + 11;
        System.out.println(fir + ", " + sec);
        if (fir == sec) {
            System.out.println("무승부!");
        } else if (fir < sec) {
            System.out.println("영희 승!");
        } else {
            System.out.println("철수 승!");
        }
        System.out.println();
    }
}
  • switch: case와 비교할 값 지정
  • case: 지정 값과 동일한지 비교
public class Main {
    public static void main(String[] args) {
        //조건문 switch 문
        // * 자바스크립트와 거의 유사함.
        int a = 10;
        switch (a) {
            case 10:
                System.out.println("10입니다.");
                //break;
            case 20:
                System.out.println("20입니다.");
                break;
            default:
                System.out.println("그외의 경우.");
                break;
        }

        // JDK 8(1.8) 주로 대세!
        // JDK 11, 17, 21, 24
        // 개발환경과 배포환경이 다른다!!
        //   -> 도커(docker) : 외부환경변수에 따르지 않다.
        int month = 3;
        switch (month) {
            case 3, 4, 5: //Java 14버전부터 가능함. 주의!
                break;
            case 6:
            case 7:
            case 8:
                break;
            case 9, 10, 11:
                break;
            case 12, 1, 2:
                break;
        }
    }
}

04 반복문

  • for: 배열의 원소를 반환, 배열이 끝나면 종료(탈출)
  • while: 조건이 false면 반복, true에 종료(탈출)
public class Main {
    public static void main(String[] args) {
        //조건문 switch 문
        // * 자바스크립트와 거의 유사함.
        int a = 10;
        switch (a) {
            case 10:
                System.out.println("10입니다.");
                //break;
            case 20:
                System.out.println("20입니다.");
                break;
            default:
                System.out.println("그외의 경우.");
                break;
        }

        // JDK 8(1.8) 주로 대세!
        // JDK 11, 17, 21, 24
        // 개발환경과 배포환경이 다른다!!
        //   -> 도커(docker) : 외부환경변수에 따르지 않다.
        int month = 3;
        switch (month) {
            case 3, 4, 5: //Java 14버전부터 가능함. 주의!
                break;
            case 6:
            case 7:
            case 8:
                break;
            case 9, 10, 11:
                break;
            case 12, 1, 2:
                break;
        }
    }
}

04-01 중첩 반복문

public class Main {
    public static void main(String[] args) {
        // 이중 반복문
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.println("i, j = " + i + ", " + j);
            }
        }

        int[][] nums = {{1, 2}, {3, 4}};
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.println("nums[i][j] = " + nums[i][j]);
            }
        }

        //별찍기
        //*****
        //*****
        //*****
        //*****
        //*****
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        //출력 예)
        //    *
        //   **
        //  ***
        // ****
        //*****
        //출력 예)
        //*******
        //*    **
        //*   * *
        //*  *  *
        //* *   *
        //**    *
        //*******
        for (int i = 1; i != 6; i++) {
            System.out.printf("%5s%n", "*".repeat(i));
        }
        System.out.println("*******");
        for (int i = 0; i != 5; i++) {
            System.out.printf("*%5s*%n", "*" + " ".repeat(i));
        }
        System.out.println("*******");
    }
}

04-02 do-while

  • do: 조건과 관계 없이 반복문을 1루프 실행
public class Main {
    public static void main(String[] args) {
        //while do-while

        //패턴
        //for( 초기식; 조건식; 증감식 ){
        //   실행문;
        //}

        //초기식;
        //while( 조건식 ){
        //  실행문;
        //  증감문; //맨마지막
        //}
        int i = 0;
        while (i < 5) {
            System.out.println(i);
            i++;
        }

        i = 0;
        do {
            System.out.println(i);
            i++;
        } while (i < 5);

        //* 적어도 한번은 실행후 조건 비교한다.
        //초기식
        //do {
        //  실행문;
        //  증감문;
        //} while( 조건식 );
    }
}

05 객체 지향 프로그래밍

  • 객체 지향 프로그래밍이란?
    객체 지향에는 클래스, 객체, 인스턴스, 상속, 인터페이스, 다형성, 추상화 등의 많은 개념 존재.

05-01 클래스와 객체

  • 클래스(Class): 객체를 생성하기 위한 설계도 또는 틀.
  • 객체(Object): 메모리에 할당된 실체. ex) 변수, 상수
  • 인스턴스(Instance): 클래스로 생성된 객체.
  • 객체 변수(instance variable): 클래스에 선언된(클래스 안에서 생성된) 변수. 인스턴스 변수, 멤버 변수, 속성이라고도 함.
  • 메서드(method): 클래스 안에 구현된 함수. 인스턴스를 통해 실행. 자바는 함수는 모두 클래스 내에 존재하기에 함수와 메서드의 구분이 없음.
class Animal{
    String name;    // 객체 변수

    public void setName(String name) {  // 메서드
        this.name = name;   // this: 현재 사용하는 인스터스를 의미(파이썬의 self)
    }
}
public class ClassStudy {
    public static void main(String[] args) {
        Animal cat = new Animal();      // 인스턴스
        System.out.println(cat+" Type: "+cat.getClass().getName());
        System.out.println(cat.name);   // 미할당 상태라 null
        cat.name = "nabi";              // 자료형은 클래스에서 선언되었기에 입력 불요.
//        int cat.name = 123;           // 오류 발생
        System.out.println(cat.name+" Type: "+cat.name.getClass().getName());
        cat.setName("kiti");            // 메서드 사용
        System.out.println(cat.name+" Type: "+cat.name.getClass().getName());
    }
}

// 결과
Animal@2f4d3709 Type: Animal
null
nabi Type: java.lang.String
kiti Type: java.lang.String

05-02 메서드(Method)

  • 매개변수: 메서드를 사용할 때 값을 받아 활용되는 변수
  • 인수: 메서드를 사용할 때 매개변수에 할당하는 값
public class MethodStudy {
    int num=0;
    int sum(int a, int b) { // a, b는 매개변수
        return a+b;         // a, b는 매개변수
    }
    void sub(int a, int b) {    // 출력값이 없을 경우 void
        System.out.println("입력값은 있지만 출력값은 없음");
    }
    void mul() {
        System.out.println("입력값도 출력값도 없음");
    }
    String div() {
        System.out.print("인스턴스 객체인 num 출력: "+this.num+"\n");
        this.num++;
        int a = 1000; int b = 5;
        int c = a/b;
        return "입력값은 없지만 출력값은 있음\n"
                +"인스턴스의 값은 영향을 받아(저장) 값이 바뀐 num 출력: "+this.num+"\n"
                +"메서드 안에서 c가 "+c+"으로 변경되었지만 매개변수라서 메서드 밖의 변수에 영향 주지 않음.\n";
    }

    public static void main(String[] args) {
        int a = 3;
        int b = 4;

        MethodStudy sample = new MethodStudy();
        int c = sample.sum(a, b);   // a, b는 인수
        System.out.println(c);
        sample.sub(a, b);
//        System.out.println(sample.sub(a, b));   // 'void' type not allowed here 오류 발생
        sample.mul();
        System.out.println(sample.div());
        System.out.println("기존 값이 그대로 유지되어 3+4+7 = 14를 반환");
        System.out.println(a+b+c);  // 기존 값이 그대로 유지됨.
    }
}

05-03 static

  • static: 정적 변수(객체)/함수를 지정할 때 사용. 프로그램 구동 시 고정된 메모리 주소에 들어가 종료 시까지 불변.
    • 사용 이유
      1. 시작점(Entry Point)를 지정할 때 사용함.
      2. 중요한 데이타를 안정적으로 저장할 때 주로 사용.
      3. 자주 사용하는 유틸성 클래스에 지정한다.(new 사용 안 해도 함수 사용 가능)
import java.util.Random;

//static 변수/함수에 대해서
//static 예약어 : 정적 변수(객체)/함수를 지정할 때 사용
//의미 : 프로그램 구동시에 고정된 메모리 번지에 들어감.(자동new)
//      프로그램 종료시까지 변경되지 않음.
//사용이유 : 1. 시작점(Entry Point)를 지정할 때 사용함.
//          2. 중요한 데이타를 안정적으로 저장할 때 주로 사용.
//          3. 자주 사용하는 유틸성 클래스에 지정한다.
//             new를 안해도 클래스 함수 사용가능
class BallFactory {
    int ballCount = 100;
    void make() {
        this.ballCount++;
        System.out.println("축구공 생산!");
    }
}
class FoodFactory {
    static int foodCount = 200;
    static void make(){
        foodCount++;
        System.out.println("도시락 생산!");
    }
}
public class Main {
    public static void main(String[] args) {
        //객체를 생성(new)해야 사용가능
        BallFactory bf = new BallFactory();
        System.out.println( bf.ballCount );
        //객체를 생성하지 않고도 사용가능(static)
        System.out.println( FoodFactory.foodCount );
        FoodFactory.make();

        //Random클래스 사용시
        Random random = new Random();
        Math.pow( 2, 3);
    }
}

05-04 접근제한자

  • 접근제한자: 클래스,함수,변수 앞에 위치하여 접근을 제한할때 사용
    • public : 같은 폴더(패키지)에서, 다른 폴더의 클래스에서 접근가능.
    • protected : 같은 폴더 + 상속관계 클래스에서 접근가능
    • default : 같은 폴더
    • private : 같은 클래스안에서 접근 가능(캡슐화,은닉). getter/setter함수통해서 접근 가능하도록 허용.
//접근제한자
//  : 클래스,함수,변수 앞에 위치하여 접근을 제한할때 사용
// * C언어 : 접근제한자가 없어서, 모든 곳에서 접근가능.
//        : 변수의 변경을 감지하기 어렵다. 유지보수가 힘들다.
// public : 같은 폴더(패키지)에서, 다른 폴더의 클래스에서 접근가능.
// protected : 같은 폴더 + 상속관계 클래스에서 접근가능
// default : 같은 폴더
// private : 같은 클래스안에서 접근 가능(캡슐화,은닉)
//         : Getter/Setter함수통해서 접근 가능하도록 허용.
//         : 은행잔고를 창구를 통해서만 접근가능하도록
class Hong {
    String name = "홍길동"; //default : 같은 폴더 + 자기 클래스 접근가능
    public int age = 20; //public : 모든폴더+상속관계+같은폴더+자기클래스
    protected int korScore = 80; //상속관계+같은폴더+자기클래스
    private int engScore = 90; //자기클래스에서만 접근가능
    //Getter/Setter 함수를 제공

    public int getEngScore() {
        return engScore;
    }

    public void setEngScore(int engScore) {
        this.engScore = engScore;
    }
}

public class Main {
    public static void main(String[] args) {
        Hong hong = new Hong();
        System.out.println( hong.name );
        System.out.println( hong.age );
        System.out.println( hong.korScore );
        //System.out.println( hong.engScore ); //접근불가

        System.out.println( hong.getEngScore() );
    }
}

05-05 상속(Inheritance) 및 생성자(Constructor)

  • 상속: 부모(다른) 클래스의 기능을 물려받는 것
  • 메서드 오버라이딩: 자식 클래스에서 동일 메서드 재구현
  • 메서드 오버로딩: 메서드명은 같지만 매개 변수가 다름.
  • 다중 상속: JAVA에선 미지원. 여러 클래스를 한번에 상속하는 것. 연쇄적인 상속은 가능.
  • 생성자: 인스턴스 생성 시 초기화하는 메서드

상속, 오버라이딩

class Animal{
    String name;    // 객체 변수

    public void setName(String name) {  // 메서드
        this.name = name;   // this: 현재 사용하는 인스터스를 의미(파이썬의 self)
    }
}

class Dog extends Animal {  // ClassStudy의 Animal 클래스 상속
    void sleep() {
        System.out.println(this.name+" zzz");   // 클래스 확장
    }
}
class Housedog extends Dog {
    public void sleep() {      // 메서드 오버라이딩
    // 오버라이딩 한 메서드는 더 좁은 권한을 줄 수 없음. protected->public은 가능하지만 public->protected 불가
        System.out.println(this.name+" zzz in house");
    }
    void sleep(int hour) {   // 메서드 오버로딩
        System.out.println(this.name+" zzz in house for "+hour+" hours");
    }
}
// 생성자
class ConstructorDog extends Housedog {
	// 기본(Default) 생성자: 필드(클래스에서 선언한 변수) 없이 생성자만 존재. 미기재 시 컴파일러가 자동 생성.
    public ConstructorDog(String name) { // 생성자는 `public className`. 산출값 미정의
        this.setName(name);
    }
    // 생성자 오버로딩(이름은 같고 인자가 다름)
    public ConstructorDog(int type) {  
        if (type==1) {
            this.setName("Jindo");
        } else if (type==2) {
            this.setName("sabsal");
        }
    }
}
	public ConstructorDog() {
        this.setName("Dog");
    }

public class Inheritance {
    public static void main(String[] args) {
        //메서드
        Dog dog = new Dog();
        dog.setName(("puppy"));
        System.out.println(dog.name);
        System.out.println(dog.getClass().getName());
        dog.sleep();
        System.out.println("==========");

        // 상속
        Animal dog2 = new Dog();
//        Dog dog2 = new Animal();    // incompatible types 오류 발생
        dog2.setName("white");
        System.out.println(dog2.name);
        System.out.println(dog2.getClass().getName());
//        dog2.sleep();               // cannot find symbol 오류 발생
        ((Dog) dog2).sleep();       // Dog로 다시 캐스팅해주어야 한다.
        System.out.println(dog2.getClass() == Dog.class);   // Animal의 기능만 있지만 Dog로 인식
        System.out.println(dog2 instanceof Dog);            // Animal의 기능만 있지만 Dog로 인식
        System.out.println("==========");

        // 오버라이딩 및 오버로딩
        Housedog dog3 = new Housedog();
        dog3.name = "happy";
        dog3.sleep();
        dog3.sleep(4);
        System.out.println("==========");

        // 생성자
        ConstructorDog dog4 = new ConstructorDog("choko");
        ConstructorDog dog5 = new ConstructorDog(2);
        dog4.sleep(3);
        dog5.sleep();
        System.out.println("==========");
    }
}

// 결과puppy
Dog
puppy zzz
==========
white
Dog
white zzz
true
true
==========
happy zzz in house
happy zzz in house for 4 hours
==========
choko zzz in house for 3 hours
sabsal zzz in house
==========

오버로딩

public class Main {
    static void echo(){
        System.out.println("echo");
    }
    static void echo(String str){
        System.out.println("echo "+str);
    }
    static void echo(int i){
        System.out.println("echo "+i);
    }
    static void echo(int i, int j){
        System.out.println("echo "+i+" "+j);
    }

    public static void main(String[] args) {
        echo();
        echo("hey~");
        echo( 10 );
        echo( 10, 20 );

        //메소드 오버로딩(Overloading), 과적
        //  : 매개변수의 타입과 갯수를 다르게 함으로
        //    함수의 기능을 확장하는 것
        //  : 같은 이름의 함수를 여러번 사용할 수 있다.
        //  : println( 정수형 ) => printlnInt
        //    println( 문자열 ) => printlnStr

        //메소드 오버라이딩(Over riding), 올라타기
        //  : 상속관계에서 자식클래스의 메소드가
        //   부모클래스의 메소드를 재정의 하는 것

        //기술면접 질문
        //1. 오버로딩 vs 오버라이드
        // 오버라이드 : 상속관계에서 자식클래스가 부모클래스
        //   메소드를 재정의하는 것.
        //2. 추상화 클래스 vs 인터페이스
        //3. 다형성
        //4. 상속
        //5. 생성자

    }
}

this & super

//상속관계에서 생성자함수 호출되는 순서
class Energy {
    int price = 1000;
    public Energy() {
        System.out.println("Energy()");
    }
    public Energy(int price) {
        this.price = price;
        System.out.println("Energy(int)");
    }
}
class WindEnergy extends Energy {
    int price = 2000;
    public WindEnergy() {
        System.out.println("WindEnergy()");
    }
    public WindEnergy(int price){
        super( price ); //부모클래스의 생성자함수 호출

        this.price = price;
        System.out.println("WindEnergy(int)");
    }
}
//this.  : 자기클래스의 필드/메소드 접근
//this( ) : 자기클래스의 생성자 함수 호출
//super. : 부모클래스의 필드/메소드 접근
//super( ) : 부모클래스의 생성자 함수 호출
public class Main {
    public static void main(String[] args) {
        //WindEnergy we = new WindEnergy();
        WindEnergy we2 = new WindEnergy(3000);
    }
}

05-06 추상 클래스(Abstract Class)와 인터페이스(Interface)

  • 추상 클래스: 인터페이스의 역할을 하며 클래스의 기능 보유한 클래스
  • 인터페이스: 일종의 규칙이자 설명. 인스턴스를 직접 생성할 수 없으며 다른 클래스를 통해 구현되거나 확장(인터페이스 포함)됨. 다중 상속 지원.

추상 클래스

//추상화 클래스 abstract class
//   : 일반 클래스 + 가상함수(추상화 메소드)
//가상함수 : 함수의 선언만 있고, 본체(코드)가 없는 것.
//        : 본체는 하위클래스에서 재정의(Override)해서 사용함.

//사용하는 이유 :
//1. 설계와 구현의 관점에서 생각
// 설계 : 건축에서 설계도의 역할, 단시간에 전체구조와 기능명세를 설계할 수 있다.
// 구현 :         시공의 역할, 실제 기능구현은 코더(Coder)가 구현한다.
//2. 기능을 정의하고 실제 구현은 나중에 한다.
//    추상화         구체화
//    그림을 그린다.  동양화를 그린다.
//                  서양화를 그린다.
//3. 코드를 업데이트시에 기존에 있던 코드를 놔두고 업데이트 가능하다.

//추상화 클래스
abstract class Picture {
    //가상함수
    abstract void draw(); //선언만 존재
    //일반함수
    void sale(){
        System.out.println("판다.");
    }
}
class Picasso extends Picture {
    @Override
    void draw() {
        System.out.println("피카소가 그림을 그린다.");
    }
}
class SuperPicasso extends Picture {
    @Override
    void draw() {
        System.out.println("수퍼피카소가 그림을 그린다.");
    }
}

public class Main {
    public static void main(String[] args) {
        Picasso picasso = new Picasso();
        picasso.draw();
        SuperPicasso superPicasso = new SuperPicasso();
        superPicasso.draw();

    }
}

인터페이스

//인터페이스 Interface
//  : 가상함수(추상메소드)만 있는 코드 뭉치

//용도 : 추상화 메소드의 설계/구현의 기능과 유사함.
//          추상화 클래스      인터페이스
//1.가상함수  있음             있음
//2.일반함수  있음             없음(default메소드)
//3.예약어    abstract class  interface
//           abstract 메소드명  abstract생략가능
//           extends          implements
//4.다중상속  불가능             가능
//5.객체생성  불가능(상속해야)    불가능(구현해야)
//6.접근제한자 public/protected/private  public만 가능
//7.필드 선언  가능             public static만 가능

interface Drawing {
    //가상함수만 사용가능
    abstract void draw();
    void sketch();
    //일반함수 사용불가
}
class Painter implements Drawing {
    @Override
    public void draw() {
        System.out.println("드로윙");
    }

    @Override
    public void sketch() {
        System.out.println("스케치");
    }
}

public class Main {
    public static void main(String[] args) {
        Painter p = new Painter();
        p.draw();
        p.sketch();
    }
}

종합

interface Predator {    // 인터페이스는 규칙.
    String getFood();   // abstract method

    default void printFood() {  // 디폴트 메서드: default로 선언. 오버라이딩 가능.
        System.out.printf("my food is %s\n", getFood());
    }
}

interface  Barkable {
    void bark();
}

interface BarkablePredator extends  Predator, Barkable {    // interface 다중 상속
}

// 추상 클래스 시작
abstract class ZooAnimal {	// 추상 클래스 선언
    String name;
    void setName(String name) { this.name = name; }
    abstract String absGetFood();  // 추상 메서드
    void absPrintFood() {   // 추상 클래스에서는 default 불가
        System.out.printf("my abstract food is %s\n", absGetFood());
    }

}
// 추상 클래스 종료

class Zoo {
    String name;

    void setName(String name) { this.name = name; }
}
class Mongkey extends Zoo implements Predator, Barkable {
    public String getFood() {       // getFood 메서드 미선언 시 추상 메서드 부재 오류
        return "apple";
    }
    public  void  bark() { System.out.println("원숭이"); }
}
class PolarBear extends Zoo implements BarkablePredator {
    public String getFood() { return "banana"; }
    public  void  bark() { System.out.println("북극곰"); }
}
class ZooKeeper {
    void feed(Predator predator) {  // 동물의 증감으로부터 독립
        System.out.println("feed "+predator.getFood());
    }
}
class Bouncer {
    void barkAnimal(Barkable animal) {
        animal.bark();
    }
}

// 추상 클래스 상속
class Tiger extends ZooAnimal implements BarkablePredator {
    public String absGetFood() { return "abstract meat"; }
    public String getFood() { return "meat"; }
    public  void  bark() { System.out.println("호랑이"); }
}

public class InterfaceStudy {
    public static void main(String[] args) {
        ZooKeeper zooKeeper = new ZooKeeper();
        Mongkey mongkey = new Mongkey();
        PolarBear polarbear = new PolarBear();
        zooKeeper.feed(mongkey);
        zooKeeper.feed(polarbear);
        mongkey.printFood();
        polarbear.printFood();

        Bouncer bouncer = new Bouncer();
        bouncer.barkAnimal((mongkey));
        bouncer.barkAnimal(polarbear);
        System.out.println("==========");

        // 추상 클래스 사용
        Tiger tiger = new Tiger();
        zooKeeper.feed(tiger);
        tiger.absPrintFood();
        tiger.printFood();
        bouncer.barkAnimal((tiger));
        ZooAnimal zooAnimal = new ZooAnimal() {
            @Override
            String absGetFood() {
                return "추상화";
            }
        };
        zooAnimal.absPrintFood();
    }
}

// 결과
feed apple
feed banana
my food is apple
my food is banana
원숭이
북극곰
==========
feed meat
my abstract food is abstract meat
my food is meat
호랑이
my abstract food is 추상화

차이점

//추상화클래스와 인터페이스 차이점

//추상화(일반) 클래스 : 다중상속은 안됨. 다단계 상속은 가능
class A {
}
class B extends A{
}
class C extends B{
}
//class D extends A, B, C {
//}

interface IA {
}
interface IB{
}
class E implements IA, IB { //다중상속
}

// 추상화 클래스 1개 상속받고, 인터페이스 다중상속(구현)하는 경우
class SupermanClass extends C implements IA, IB {

}


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

    }
}
  • ChatGPT 응답

인터페이스와 추상 클래스의 주요 차이점

항목인터페이스 (Interface)추상 클래스 (Abstract Class)
사용 목적다중 상속을 통해 공통 기능의 계약 정의, 특정 행동의 강제 구현공통된 기본 구현 제공, 일부 구현된 메서드를 자식 클래스에서 상속받을 때
메서드기본적으로 추상 메서드만 (자바 8부터 default 메서드 가능)추상 메서드와 구현된 메서드 모두 가능
필드상수만 가질 수 있음 (public static final)변수 가질 수 있음 (다양한 접근 제어자 가능)
다중 상속가능 (여러 인터페이스 구현 가능)불가능 (단일 상속만 가능)
생성자없음 (인터페이스는 생성자가 없기 때문)가능 (상속받은 클래스에서 생성자 호출 가능)
사용 예시특정 클래스가 여러 다른 클래스에서 공통된 기능을 가져야 할 때공통된 기능을 상속하고, 일부 기능만 자식 클래스에서 구현해야 할 때

언제 인터페이스를 사용하고, 언제 추상 클래스를 사용해야 할까?

  • 인터페이스를 사용하는 경우:

    • 다중 상속이 필요한 경우 (예: ClassA와 ClassB에서 공통된 기능을 여러 클래스에서 구현해야 할 때)
    • 기능의 계약을 정의하고, 구현은 각 클래스에서 다르게 하고자 할 때 (예: Runnable, Comparable, Serializable 인터페이스 등)
    • 일관된 API를 제공하려고 할 때 (메서드 시그니처만 정의하고, 각 클래스에서 어떻게 처리할지는 자유롭게 구현)
  • 추상 클래스를 사용하는 경우:

    • 공통된 구현을 제공하고, 자식 클래스가 이를 공유해야 할 때
    • 일부 구현된 메서드를 자식 클래스에서 활용하고, 필요한 메서드만 구현하도록 유도할 때
    • 상태를 유지하는 필드나 메서드가 필요한 경우

결론:

  • 인터페이스는 주로 다중 상속과 행위 정의를 위해 사용되며, 객체 간의 공통적인 계약을 정의할 때 유용합니다.
  • 추상 클래스는 공통된 기본 구현과 상태(필드)가 필요할 때, 그리고 단일 상속을 통해 공통적인 기능을 자식 클래스들에 제공하고자 할 때 사용됩니다.

05-07 다형성(Polymorphism)

  • 다형성: 하나의 객체가 여러 개의 자료형 타입을 가질 수 있는(자식클래스 객체가 자기클래스 또는 부모클래스의 타입을 모두 가질 수 있음)
//다형성 : 폴리모피즘
//   : 자식클래스 객체가 자기클래스 또는 부모클래스의 타입을
//      모두 가질 수 있는 것.
//이유 : 타입의 유연성을 가지기 위해서.
//     : 타입이 정확하지 않더라도 객체(참조변수)를 전달 가능.
class Parent {
    String name = "Parent";
    void parentMethod(){
        System.out.println("Parent 내 이름은 " + this.name);
    }
}
class Child extends Parent {
    String name = "Child";
    void childMethod(){
        System.out.println("Child 내 이름은 " + this.name);
    }
}
public class Main {
    public static void main(String[] args) {
        Parent p1 = new Parent();
        System.out.println( p1.name );
        Child c1 = new Child();
        System.out.println( c1.name );

        //1. 업캐스팅(Up Cast) : 자식객체가 부모클래스 타입을 가지는 것
        //1) 대입연산자를 통해서
        Parent p2 = new Child();
        System.out.println( p2.name );
        //2) 강제형변환 연산자를 통해서
        Parent p3 = (Parent) c1;
        System.out.println( p3.name );

        //2. 다운캐스팅(Down Cast) : 자식객체가 자식클래스 타입을 가지는 것
        Child c2 = (Child)p2;
        System.out.println( c2.name );

        //4가지 형태
        Parent a = new Parent();
        Child b = new Child();
        Parent c = new Child();
        Child d = (Child)c;

        //Child e = new Parent(); 불가능하다.
    }
}
class A {
    public void msg() {
        System.out.println("A message");
    }
    public void msg2() {
        System.out.println("A message2");
    }
}

class B extends A{
    public void msg() {
        System.out.println("B message");
    }
}

class C extends B {
}
public class Tmp {
    public static void main(String[] args) {
        C temp = new C();
        temp.msg();			// 마지막에 상속된 메서드 실행
        temp.msg2();        // B에서 구현하지 않아도 A의 메서드까지 모두 상속
        A temp3 = new B();
        temp3.msg();        // B의 메서드 실행
        System.out.println(temp3.getClass() == A.class);    // false: 참조하는 실제 객체의 클래스 비교
        System.out.println(temp3 instanceof A);             // true:  A의 인스턴스인지 확인. GPT가 알려준 차이인데 잘 모르겠다.
        System.out.println(temp3.getClass() == B.class);
        System.out.println(temp3 instanceof B);
    }
}

// 결과
B message
A message2
B message
false
true
true
true
class People {
    void think(){
        System.out.println("생각한다.");
    }
}
class Man extends People {
    @Override
    void think() {
        System.out.println("남자가 생각한다.");
    }
    void shave() {
        System.out.println("면도한다.");
    }
}
class Woman extends People {
    @Override
    void think() {
        System.out.println("여자가 생각한다.");
    }
    void makeup(){
        System.out.println("화장한다.");
    }
}

public class Main {
    public static void main(String[] args) {
        //1.업캐스팅
        People people = new Man();
        people.think();
        //2.다운캐스팅
        ((Man)people).shave();

        //다형성을 이용하여 Man객체, Woman객체도 전달할 수 있다.
        myFunc( new People() );
        myFunc( new Man() );
        myFunc( new Woman() );
    }

    static void myFunc( People p ) {
        //instanceof 연산자 : 객체 타입을 확인하는 연산자
        if( p instanceof Man ) {
            Man m = (Man)p;
            m.shave();
        }
        else if( p instanceof Woman) {
            Woman w = (Woman)p;
            w.makeup();
        }
    }

}

05-08 싱글톤(Singleton)

  • 특정 클래스의 인스턴스가 오직 하나만 존재하도록 하는 것
//싱글톤(Singleton)
//  : 프로그램안에서의 유일한 클래스 객체
//  : new를 통해서 여러개의 객체를 반복적으로 찍어낼 수 있다.
//  : 예) 붕어빵1, 붕어빵2, ....
//      절대붕어빵(유일한 붕어빵)
//유일한 객체가 필요한 이유
//  : 유일한 정보를 저장하기 위해서
class FishBun { //일반붕어빵
    int bunNo = 10;
}
class UniqueFishBun {
    int bunNo = 30;
    private static UniqueFishBun singleton; //null
    static UniqueFishBun getInstance() {
        if (singleton == null) {
            singleton = new UniqueFishBun();
        }
        return singleton;
    }
}
public class Main {
    public static void main(String[] args) {
        UniqueFishBun uBun1 = UniqueFishBun.getInstance();
        UniqueFishBun uBun2 = UniqueFishBun.getInstance();
        System.out.println( uBun1 ); //119d7047
        System.out.println( uBun2 ); //119d7047
        uBun1.bunNo = 40;
        System.out.println( uBun1.bunNo );
        System.out.println( uBun2.bunNo );

        FishBun bun1 = new FishBun();
        FishBun bun2 = new FishBun();
        System.out.println(bun1); //4eec7777
        System.out.println(bun2); //3b07d329
        bun1.bunNo = 20;
        System.out.println( bun1.bunNo);
        System.out.println( bun2.bunNo);
        //일반 객체는 일관된 데이터를 저장하기 어렵다.
        //dynamic 객체는 Heap 영역에 저장된다.
        //GC(Garbage Collector)가 자동으로 메모리를 자동회수한다.
    }
}

05-08 익명 객체(Anonymous Object)

  • 일회성 코드로 재사용하지 않을 경우 사용됨.
//익명 객체(이름없는 객체 - Anonymous Object)
//   : 일회성 메소드(코드뭉치) 재정의시 사용한다.
//   : 한번 쓰고 버릴 코드에 굳이 이름을 붙여서 사용할 필요가 없다.
interface NormalCar {
    void run();
}
//class SuperCar implements NormalCar {
//    @Override
//    public void run() {
//        System.out.println("수퍼카가 달린다.");
//    }
//}
public class Main {
    public static void main(String[] args) {
//        SuperCar sc = new SuperCar();
//        sc.run();
        //일회성 익명 인터페이스 구현 객체를 생성한다.
        NormalCar normalCar = new NormalCar(){
            @Override
            public void run(){
                System.out.println("수퍼카가 달린다.");
            }
        };
        normalCar.run();
    }
}

05-09 Class 클래스

  • Class 클래스: 클래스 자체에 대한 정보를 담고 있는 객체
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) throws ClassNotFoundException {
        // Class 클래스: 클래스 정보를 담고 있는 클래스
        //            : 멤버변수, 멤버함수, 어노테이션 정보 등
        Class c1 = String.class;
        System.out.println("c1 = " + c1);
        String str = new String();
        System.out.println("str = " + str.getClass());
        Class c2 = str.getClass();
        System.out.println("c2 = " + c2);
        Class c3 = Class.forName("java.lang.String");
        System.out.println("c3 = " + c3);

        Constructor[] cons = c3.getConstructors();
        System.out.println("Constructor list ------------------");
        for (Constructor con: cons) {
            System.out.println( con);
        }

        Method[] methods = c3.getMethods();
        System.out.println("Method list ------------------");
        for (Method m: methods) {
            System.out.println(m);
        }

        Annotation[] annotations = c3.getAnnotations();
        System.out.println("Annotation list ------------------");
        for (Annotation a: annotations) {
            System.out.println(a);
        }

        Field[] fields = c3.getFields();
        System.out.println("Field list ------------------");
        for (Field f: fields) {
            System.out.println(f);
        }
    }
}

05-10 람다식(Lambda Expression)

  • 함수형 인터페이스 형태로 선언하여 화살표 연산자로 사용.
//람다식( Lambda Expression )
//   : JDK 1.8부터 지원하기 시작
//   : 일반 변수는 값을 담는다. 값변수:실제값, 참조변수:주소값
//   : 함수형 변수 = 코드를 담는다. 함수:코드의 선언/호출
//   : 3세대 언어인 JS, 코틀린, 스위프트, Go 언어들에서는 함수형 변수를 지원.
//   : 자바에서 코드를 변수형태로 담아서 전달(매개변수)하기 위해 새롭게 설계.
//   : 억지로 인터페이스 문법을 차용하여 사용한다.
//   : 자바는 클래스와 객체에 변수+함수코드 담고 있기 때문에, 객체를 전달하면
//      코드전달을 할 수 있기에, 람다식은 그다지 유용하지 않다.

//람다식 선언 : 함수형 인터페이스 형태로 선언
//      구현 : -> 화살표연산자를 이용

// @FunctionalInterface : 람다식 선언시에만 사용하는 어노테이션(컴파일 지시어)
@FunctionalInterface
interface MyFunc1 {
    int calc(int x, int y); //가상함수
}

public class Main {
    public static void main(String[] args) {
        MyFunc1 f1 = (int x, int y) -> {
            return x + y;
        };
        MyFunc1 f2 = (int x, int y) -> x + y;
        System.out.println(f1.calc(10, 20));
        System.out.println(f2.calc(10, 20));

        //함수형 변수 : 코드를 담아서 함수의 매개변수로 전달하기 위한 용도.
        execFunc( f1 );
    }

    static void execFunc(MyFunc1 func) {
        System.out.println(func.calc(30, 40));
    }
}

05-11 재귀함수

  • 재귀함수(Recursive Function): 스스로를 반복 호출하여 사용하는 함수
public class ex62 {
    public static void main(String[] args) {
        //재귀함수 (Recursive Function)
        //   : 자기가 자기를 호출하는 함수
        System.out.println("메인함수 시작");
        myFunc();
        System.out.println("메인함수 종료");
        return;
    }//main

    static int count = 0;

    static void myFunc() {
        System.out.println("MyFunc 시작:" + count);
        count++;
        //탈출조건
        if (count > 2) {
            count--;
            System.out.println("탈출1:count=" + count);
            return;
        }
        myFunc();
        count--;
        System.out.println("탈출2:count=" + count);
        return;
    }
}

※ 원래는 길벗 책을 받아서 이걸로만 하려 했는데 기초 부분에 대해서는 책이 별로라 이전에 독학했던 점프 투 자바도 참고했다.

출처: 한국경제신문 K-Digital Training - toss bank
첨고 서적:
최원효 지음, 입문자의 눈높이에 맞춰 문법과 개념을 설명하는 자바 입문서 코딩 자율학습 자바 입문, 길벗, 2024년
박응용 지음, Do it! 점프 투 자바, 이지스퍼블리싱, 2023년
박응용 지음, Do it! 점프 투 자바(위키독스 전자책), 위키독스, 최종 편잡일: 2025년 02월 21일

profile
데이터, 풀스택

0개의 댓글