Hard deck/Basic

java : 점프 투 자바 : 0 ~ 10

서버관리자 페페 2022. 5. 29. 21:21

0. 구구단 프로그램

public class GuGu {
    public void dan(int n) {
        for (int i = 1; i < 10; i++) {
            System.out.println(n * i);
        }
    }

    public static void main(String[] args) {
        GuGu gugu = new GuGu();
        for (int i = 2; i < 10; i++) { 
            gugu.dan(i);
        }
    }
}

 

1. sourcecode structure 

/* 클래스 블록 */
public class 클래스명 {

    /* 메소드 블록 */
    [public|private|protected] [static] (리턴자료형|void) 메소드명1(입력자료형 매개변수, ...) {
        명령문(statement);
        ...
    }

    /* 메소드 블록 */
    [public|private|protected] [static] (리턴자료형|void) 메소드명2(입력자료형 매개변수, ...) {
        명령문(statement);
        ...
    }

    ...
}

 

2.

boolean -1 

int base = 180;
int height = 185;
boolean isTall = height > base;

if (isTall) {
    System.out.println("키가 큽니다.");
}

 

 

3.

boolean-2

int i = 3;
boolean isOdd = i % 2 == 1;
System.out.println(isOdd);  // true 출력

 

4.

string 

String a = "hello";
String b = new String("hello");
System.out.println(a.equals(b));  // true
System.out.println(a == b);  // false

 

 

5.

String 2  - string 내장 메소드

 

String a = "Hello Java";
System.out.println(a.indexOf("Java"));  // 6 출력
String a = "Hello Java";
System.out.println(a.contains("Java"));  // true 출력
String a = "Hello Java";
System.out.println(a.charAt(6));  // "J" 출력
String a = "Hello Java";
System.out.println(a.replaceAll("Java", "World"));  // Hello World 출력
String a = "Hello Java";
System.out.println(a.substring(0, 4));  // Hell 출력
String a = "Hello Java";
System.out.println(a.toUpperCase());  // HELLO JAVA 출력

(모두 소문자로 변경할때는 toLowerCase를 사용한다.)

String a = "a:b:c:d";
String[] result = a.split(":");  // result는 {"a", "b", "c", "d"}

 

 

6.

String Formattaing

System.out.println(String.format("I eat %d apples.", 3));  // "I eat 3 apples." 출력
System.out.println(String.format("I eat %s apples.", "five"));  // "I eat five apples." 출력
int number = 3;
System.out.println(String.format("I eat %d apples.", number));  // "I eat 3 apples." 출력
int number = 10;
String day = "three";

// "I ate 10 apples. so I was sick for three days." 출력
System.out.println(String.format("I ate %d apples. so I was sick for %s days.", number, day));

 

System.out.println(String.format("Error is %d%%.", 98));  // "Error is 98%." 출력

 

7.

StringBuffer - append

 

(Stringbuffer 버전)

StringBuffer sb = new StringBuffer();  // StringBuffer 객체 sb 생성
sb.append("hello");
sb.append(" ");
sb.append("jump to java");
String result = sb.toString();
System.out.println(result);

- multi thread에서 안전

 

(string 버전)

 

 

String result = "";
result += "hello";
result += " ";
result += "jump to java";
System.out.println(result);

- buffer보다 가볍지만 immutable하기에, 할때마다 객체 생성

- 문자열 변경 작업이 많을 때에는 Buffer, 변경이 거의 없는 경우는 String 사용

 

(StringBuilder 버전)

StringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append(" ");
sb.append("jump to java");
String result = sb.toString();
System.out.println(result);

- Buffer보다 성능 우수 > 동기화 고려할 필요없는 상황에서 사용

 

insert

StringBuffer sb = new StringBuffer();
sb.append("jump to java");
sb.insert(0, "hello ");
System.out.println(sb.toString());

substring

StringBuffer sb = new StringBuffer();
sb.append("Hello jump to java");
System.out.println(sb.substring(0, 4));

 

 

8.

Array

String[] weeks = new String[7];
weeks[0] = "월";
weeks[1] = "화";
weeks[2] = "수";
weeks[3] = "목";
weeks[4] = "금";
weeks[5] = "토";
weeks[6] = "일";
String[] weeks = {"월", "화", "수", "목", "금", "토", "일"};
for (int i=0; i<weeks.length; i++) {
    System.out.println(weeks[i]);
}

 

9.

Arraylist

import java.util.ArrayList;

public class Sample {
    public static void main(String[] args) {
        ArrayList pitches = new ArrayList();
        pitches.add("138");
        pitches.add("129");
        pitches.add("142");
    }
}

(add)

pitches.add(0, "133");    // 첫번째 위치에 133 삽입.

(get)

 

 

System.out.println(pitches.get(1));

(size)

System.out.println(pitches.size());

 

(contains)

System.out.println(pitches.contains("142"));

 

(remove(객체) > 삭제된 결과 boolean return)

System.out.println(pitches.remove("129"));

(remove(key) > 삭제된 항목 return)

System.out.println(pitches.remove(0));

 

10.

Generics

 

(사용하지 않을 때)

ArrayList pitches = new ArrayList();
aList.add("138");
aList.add("129");

String one = (String) pitches.get(0);
String two = (String) pitches.get(1);

(사용할 때)

ArrayList<String> pitches = new ArrayList<>();
aList.add("138");
aList.add("129");

String one = pitches.get(0);  // 형 변환이 필요없다.
String two = pitches.get(1);  // 형 변환이 필요없다.

 

 

11.

String data가 존재할 때 ArrayList

import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        String[] data = {"138", "129", "142"};  // 이미 투구수 데이터 배열이 있다.
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList(data));
        System.out.println(pitches);  // [138, 129, 142] 출력
    }
}

 

import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        System.out.println(pitches);
    }
}

 

12.

List 정렬

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        pitches.sort(Comparator.naturalOrder());  // 오름차순으로 정렬
        System.out.println(pitches);  // [129, 138, 142] 출력
    }
}

 

  • 오름차순(순방향) 정렬 - Comparator.naturalOrder()
  • 내림차순(역방향) 정렬 - Comparator.reverseOrder()

 

13.

Array > 구분된 String

 

일반

import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        String result = "";
        for (int i = 0; i < pitches.size(); i++) {
            result += pitches.get(i);
            result += ",";  // 콤마를 추가한다.
        }
        result = result.substring(0, result.length() - 1);  // 마지막 콤마는 제거한다.
        System.out.println(result);  // 138,129,142 출력
    }
}

 

String.join의 사용

import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> pitches = new ArrayList<>(Arrays.asList("138", "129", "142"));
        String result = String.join(",", pitches);
        System.out.println(result);  // 138,129,142 출력
    }
}
public class Sample {
    public static void main(String[] args) {
        String[] pitches = new String[]{"138", "129", "142"};
        String result = String.join(",", pitches);
        System.out.println(result);  // 138,129,142 출력
    }
}

 

14. 

Map

import java.util.HashMap;

public class Sample {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("people", "사람");
        map.put("baseball", "야구");
    }
}

 

System.out.println(map.get("people"));  // "사람" 출력

 

System.out.println(map.containsKey("people"));  // true 출력
System.out.println(map.remove("people"));  // "사람" 출력
System.out.println(map.size());  // 1 출력

 

import java.util.HashMap;

public class Sample {
    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put("people", "사람");
        map.put("baseball", "야구");
        System.out.println(map.keySet());  // [baseball, people] 출력
    }
}

Set 자료형은 다음과 같이 List 자료형으로 바꾸어 사용할수도 있다.

List<String> keyList = new ArrayList<>(map.keySet());

 

  • LinkedHashMap은 입력된 순서대로 데이터를 저장하는 특징을 가지고 있다.
  • TreeMap은 입력된 key의 오름차순 순서로 데이터를 저장하는 특징을 가지고 있다.

 

 

15.

Set

import java.util.Arrays;
import java.util.HashSet;

public class Sample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("Jump");
        set.addAll(Arrays.asList("To", "Java"));
        System.out.println(set);  // [Java, To, Jump] 출력
    }
}

제거 : remove

  • TreeSet - 오름차순으로 값을 정렬하여 저장하는 특징이 있다.
  • LinkedHashSet - 입력한 순서대로 값을 정렬하여 저장하는 특징이 있다.

 

교집합

import java.util.Arrays;
import java.util.HashSet;

public class Sample {
    public static void main(String[] args) {
        HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
        HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));

        HashSet<Integer> intersection = new HashSet<>(s1);  // s1으로 intersection 생성
        intersection.retainAll(s2);  // 교집합 수행
        System.out.println(intersection);  // [4, 5, 6] 출력
    }
}

 

import java.util.Arrays;
import java.util.HashSet;

public class Sample {
    public static void main(String[] args) {
        HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
        HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));

        HashSet<Integer> union = new HashSet<>(s1);  // s1으로 union 생성
        union.addAll(s2); // 합집합 수행
        System.out.println(union);  // [1, 2, 3, 4, 5, 6, 7, 8, 9] 출력
    }
}
import java.util.Arrays;
import java.util.HashSet;

public class Sample {
    public static void main(String[] args) {
        HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
        HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));

        HashSet<Integer> substract = new HashSet<>(s1);  // s1으로 substract 생성
        substract.removeAll(s2); // 차집합 수행
        System.out.println(substract);  // [1, 2, 3] 출력
    }
}

 

16.

Enum

public class Sample {
    enum CoffeeType {
        AMERICANO,
        ICE_AMERICANO,
        CAFE_LATTE
    };

    public static void main(String[] args) {
        System.out.println(CoffeeType.AMERICANO);  // AMERICANO 출력
        System.out.println(CoffeeType.ICE_AMERICANO);  // ICE_AMERICANO 출력
        System.out.println(CoffeeType.CAFE_LATTE);  // CAFE_LATTE 출력
    }
}

또는 다음과 같이 반복문에서 사용할수도 있다.

public class Sample {
    enum CoffeeType {
        AMERICANO,
        ICE_AMERICANO,
        CAFE_LATTE
    };

    public static void main(String[] args) {
        for(CoffeeType type: CoffeeType.values()) {
            System.out.println(type);  // 순서대로 AMERICANO, ICE_AMERICANO, CAFE_LATTE 출력
        }
    }
}

 

  • 매직넘버(1과 같은 숫자 상수값)를 사용할 때보다 코드가 명확해 진다.
  • 잘못된 값을 사용함으로 인해 발생할수 있는 위험성이 사라진다.

 

17.

형변환

public class Sample {
    public static void main(String[] args) {
        String num = "123";
        int n = Integer.parseInt(num);
        System.out.println(n);  // 123 출력
    }
}

이번에는 반대로 정수 123을 문자열 "123"으로 바꾸는 방법에 대해서 알아보자. 정수를 문자열로 바꾸는 가장 쉬운 방법은 정수 앞에 빈문자열("")을 더해 주는 것이다.

public class Sample {
    public static void main(String[] args) {
        int n = 123;
        String num = "" + n;
        System.out.println(num);  // 123 출력
    }
}

또는 다음과 같이 변환할 수도 있다.

public class Sample {
    public static void main(String[] args) {
        int n = 123;
        String num1 = String.valueOf(n);
        String num2 = Integer.toString(n);
        System.out.println(num1);  // 123 출력
        System.out.println(num2);  // 123 출력
    }
}

실제 프로젝트에서 정수와 문자열 사이의 변환은 매우 자주 사용한다.

 

18.

Final

 

public class Sample {
    public static void main(String[] args) {
        final int n = 123;  // final 로 설정하면 값을 바꿀수 없다.
        n = 456;  // 컴파일 에러 발생
    }
}

리스트의 경우도 final로 선언시 재할당은 불가능하다.

import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        final ArrayList<String> a = new ArrayList<>(Arrays.asList("a", "b"));
        a = new ArrayList<>(Arrays.asList("c", "d"));  // 컴파일 에러 발생
    }
}

final은 프로그램 수행 도중 그 값이 변경되면 안되는 상황에 사용한다.


리스트의 경우 final로 선언시 리스트에 값을 더하거나(add) 빼는(remove) 것은 가능하다. 다만 재할당만 불가능할 뿐이다. 만약 그 값을 더하거나 빼는 것도 불가능하게 하고 싶은 경우에는 List.of로 수정이 불가능한 리스트(Unmodifiable List)를 생성해야 한다.

import java.util.List;

public class Sample {
    public static void main(String[] args) {
        final List<String> a = List.of("a", "b");
        a.add("c");  // UnsupportedOperationException 발생
    }
}
 
 
19.
if문 
x < y x가 y보다 작다
x > y x가 y보다 크다
x == y x와 y가 같다
x != y x와 y가 같지 않다
x >= y x가 y보다 크거나 같다
x <= y x가 y보다 작거나 같다

 

 

int money = 2000;
boolean hasCard = true;

if (money>=3000 || hasCard) {
    System.out.println("택시를 타고 가라");
} else {
    System.out.println("걸어가라");
}

 

  • x || y - x와 y 둘 중 적어도 하나가 참이면 참이다
  • x && y - x와 y 모두 참이어야 참이다
  • !x - x가 거짓이면 참이다

 

CONTAINS

boolean hasCard = true;
ArrayList<String> pocket = new ArrayList<String>();
pocket.add("paper");
pocket.add("handphone");

if (pocket.contains("money")) {
    System.out.println("택시를 타고 가라");
}else if(hasCard) {
    System.out.println("택시를 타고 가라");
}else {         
    System.out.println("걸어가라");
}



20

switch > case

public class Sample {
    public static void main(String[] args) {
        int month = 8;
        String monthString = "";
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

 

21

while > if(exit)

 

int treeHit = 0;
while (treeHit < 10) {
    treeHit++;
    System.out.println("나무를  " + treeHit + "번 찍었습니다.");
    if (treeHit == 10) {
        System.out.println("나무 넘어갑니다.");
    }
}

 

무한루프

while (true) {
    System.out.println("Ctrl-C를 눌러야 while문을 빠져 나갈 수 있습니다.");
}

 

break

int coffee = 10;
int money = 300;

while (money > 0) {
    System.out.println("돈을 받았으니 커피를 줍니다.");
    coffee--;
    System.out.println("남은 커피의 양은 " + coffee + "입니다.");
    if (coffee == 0) {
        System.out.println("커피가 다 떨어졌습니다. 판매를 중지합니다.");
        break;
    }
}

if 조건문 뒤에 ; 붇는다면 루프문이 안이어짐. 주의!

 

continue를 활용한 홀수 출력

int a = 0;
while (a < 10) {
    a++;
    if (a % 2 == 0) {
        continue;  // 짝수인 경우 조건문으로 돌아간다.
    }
    System.out.println(a);  // 홀수만 출력된다.
}

 

22

for 

(basic)

int[] marks = {90, 25, 67, 45, 80};
for(int i=0; i<marks.length; i++) {
    if (marks[i] >= 60) {
        System.out.println((i+1)+"번 학생은 합격입니다.");
    }else {
        System.out.println((i+1)+"번 학생은 불합격입니다.");
    }
}

 

 

(continue)

int[] marks = {90, 25, 67, 45, 80};
for(int i=0; i<marks.length; i++) {
    if (marks[i] < 60) {
        continue;
    }
    System.out.println((i+1)+"번 학생 축하합니다. 합격입니다.");
}

특정 구간 미출력 - 합격자 명단

 

(이중 for 문)

for(int i=2; i<10; i++) {
    for(int j=1; j<10; j++) {
        System.out.print(i*j+" ");
    }
    System.out.println("");
}

 

위에서 System.out.print System.out.println을 구분하여 사용했다. System.out.print은 줄바꿈문자(\n)을 포함하지 않고 출력을 하고 System.out.println은 마지막에 줄바꿈문자(\n)을 포함하여 출력하는 차이가 있다. 즉 2단, 3단 처럼 한 단이 끝날때만 줄바꿈 문자를 출력하기 위해 위와 같이 구분하여 사용한 것이다.

 

 

23

for each

import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        ArrayList<String> numbers = new ArrayList<>(Arrays.asList("one", "two", "three"));
        for (String number : numbers) {
            System.out.println(number);
        }
    }
}

 

 

24

객체지향 프로그래밍 기초

class Calculator {
    int result = 0;

    int add(int num) {
        result += num;
        return result;
    }
}


public class Sample {
    public static void main(String[] args) {
        Calculator cal1 = new Calculator();  // 계산기1 객체를 생성한다.
        Calculator cal2 = new Calculator();  // 계산기2 객체를 생성한다.

        System.out.println(cal1.add(3));
        System.out.println(cal1.add(4));

        System.out.println(cal2.add(3));
        System.out.println(cal2.add(7));
    }
}
static이 없음에 주의

 

25

객체 변수와 객체 메소드

class Animal {
    String name;

    public void setName(String name) {
        this.name = name;
    }
}

public class Sample {
    public static void main(String[] args) {
        Animal cat = new Animal();
        cat.setName("boby");  // 메소드 호출
        System.out.println(cat.name);
    }
}

 

26

메소드 1 : 입 O 출 O

public class Sample {
    int sum(int a, int b) {  // a, b 는 매개변수
        return a+b;
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        int c = sample.sum(3, 4);  // 3, 4는 인수

        System.out.println(c);  // 7 출력
    }
}

 

27

메소드 2 : 입X 출 O

public class Sample {
    String say() {
        return "Hi";
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        String a = sample.say();
        System.out.println(a);  // "Hi" 출력
    }
}

 

28

메소드 3 : 입 O, 출 X

public class Sample {
    void sum(int a, int b) {
        System.out.println(a+"과 "+b+"의 합은 "+(a+b)+"입니다.");
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        sample.sum(3, 4);
    }
}

println문 안에 a+b를 괄호로 묶지 않으면 ab로 출력

괄호로 묶으면 산술값이 나온다는 것에 유의

 

29

메소드 4 : 입 X, 출 X

public class Sample {
    void say() {
        System.out.println("Hi");
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        sample.say();
    }
}

 

 

30

void method에서 return으로 구멍 만들기

public class Sample {
    void sayNick(String nick) {
        if ("fool".equals(nick)) {
            return;
        }
        System.out.println("나의 별명은 "+nick+" 입니다.");
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        sample.sayNick("angel");
        sample.sayNick("fool");  // 출력되지 않는다.
    }
}

 

31

객체 변수의 구분

 

(작동하지 않음)

public class Sample {
    void varTest(int a) {
        a++;
    }

    public static void main(String[] args) {
        int a = 1;
        Sample sample = new Sample();
        sample.varTest(a);
        System.out.println(a);
    }
}

 

(작동함)

 

public class Sample {
    int varTest(int a) {
        a++;
        return a;
    }

    public static void main(String[] args) {
        int a = 1;
        Sample sample = new Sample();
        a = sample.varTest(a);
        System.out.println(a);
    }
}

 

(작동함)

public class Sample {

    int a;  // 객체변수 a

    void varTest(Sample sample) {
        sample.a++;
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        sample.a = 1;
        sample.varTest(sample);
        System.out.println(sample.a);
    }
}

 

32

THIS 활용하

public class Sample {

    int a;  // 객체변수 a

    void varTest() {
        this.a++;
    }

    public static void main(String[] args) {
        Sample sample = new Sample();
        sample.a = 1;
        sample.varTest();
        System.out.println(sample.a);  // 2 출력
    }
}

 

33

Call by value : 특정 라인의 메소드가 아닌, 공간을 그대로로 가져오기

class Updater {
    void update(Counter counter) {
        counter.count++;
    }
}

class Counter {
    int count = 0;  // 객체변수
}

public class Sample {
    public static void main(String[] args) {
        Counter myCounter = new Counter();
        System.out.println("before update:"+myCounter.count);
        Updater myUpdater = new Updater();
        myUpdater.update(myCounter);
        System.out.println("after update:"+myCounter.count);
    }
}

 

update 메소드에 int 자료형을 전달받는다면, 0,0으로 나옴에 주의한다

 

34

extends 및 기능의 확장

class Animal {
    String name;

    void setName(String name) {
        this.name = name;
    }
}

class Dog extends Animal {
    void sleep() {
        System.out.println(this.name+" zzz");
    }
}

public class Sample {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.setName("poppy");
        System.out.println(dog.name);  // poppy 출력
        dog.sleep();  // poppy zzz 출력
    }
}

 

 

Object animal = new Animal();  // Animal is a Object
Object dog = new Dog();  // Dog is a Object

 

 

35

Overriding and Overloading

class Animal {
    String name;

    void setName(String name) {
        this.name = name;
    }
}

class Dog extends Animal {
    void sleep() {
        System.out.println(this.name + " zzz");
    }
}

class HouseDog extends Dog {
    void sleep() {
        System.out.println(this.name + " zzz in house");
    }

    void sleep(int hour) {
        System.out.println(this.name + " zzz in house for " + hour + " hours");
    }
}

public class Sample {
    public static void main(String[] args) {
        HouseDog houseDog = new HouseDog();
        houseDog.setName("happy");
        houseDog.sleep();  // happy zzz in house 출력
        houseDog.sleep(3);  // happy zzz in house for 3 hours 출력
    }
}

실행하면 다음과 같은 결과가 출력될 것이다.

 

36

Counstructor

(... 생략 ...)

class HouseDog extends Dog {
    HouseDog(String name) {
        this.setName(name);
    }

    void sleep() {
        System.out.println(this.name + " zzz in house");
    }

    void sleep(int hour) {
        System.out.println(this.name + " zzz in house for " + hour + " hours");
    }
}

(... 생략 ...)

- new class 뒤에 나오는 흐름을 규정

- 아무것도 없다면 = default 생성자(컴파일러에서 자동으로 추가)

 

37

constructor overloading

HouseDog 클래스의 객체는 다음처럼 두 가지 방법으로 생성할 수 있다.

HouseDog happy = new HouseDog("happy");  // 문자열로 생성
HouseDog yorkshire = new HouseDog(1);  // 숫자값으로 생성

 

 
class Animal {
    String name;

    void setName(String name) {
        this.name = name;
    }
}

class Dog extends Animal {
    void sleep() {
        System.out.println(this.name + " zzz");
    }
}

class HouseDog extends Dog {
    HouseDog(String name) {
        this.setName(name);
    }

    HouseDog(int type) {
        if (type == 1) {
            this.setName("yorkshire");
        } else if (type == 2) {
            this.setName("bulldog");
        }
    }

    void sleep() {
        System.out.println(this.name + " zzz in house");
    }

    void sleep(int hour) {
        System.out.println(this.name + " zzz in house for " + hour + " hours");
    }
}

public class Sample {
    public static void main(String[] args) {
        HouseDog happy = new HouseDog("happy");
        HouseDog yorkshire = new HouseDog(1);
        System.out.println(happy.name);  // happy 출력
        System.out.println(yorkshire.name);  // yorkshire 출력
    }
}

 

38

Interface 

 

interface Predator {
    String getFood();
}

(... 생략 ...)

 

(... 생략 ...)

class Tiger extends Animal implements Predator {
    public String getFood() {
        return "apple";
    }
}

class Lion extends Animal implements Predator {
    public String getFood() {
        return "banana";
    }
}

(... 생략 ...)

※ 인터페이스의 메소드는 항상 public으로 구현해야 한다.

 

(... 생략 ...)

class ZooKeeper {
    void feed(Predator predator) {
        System.out.println("feed "+predator.getFood());
    }
}

(... 생략 ...)

Animal클래스에 getFood 를 추가 / 각 동물객체에서 getFood를 오버라이딩 / ZooKeeper의 feed가 Animal을 파라미터로 사용해도 작동

그렇지만 interface에 구현하는것은 해당 메소드를 반드시 구현해야한다

 

 

 

39

Interface - dafault method

interface Predator {
    String getFood();

    default void printFood() {
        System.out.printf("my food is %s\n", getFood());
    }
}

- 원래 구현체를 가질 수 없지만, default에서는 가능

- Overriding 가능

 

 

 

40

Interface - static method

interface Predator {
    String getFood();

    default void printFood() {
        System.out.printf("my food is %s\n", getFood());
    }

    int LEG_COUNT = 4;  // 인터페이스 상수

    static int speed() {
        return LEG_COUNT * 30;
    }
}

 

Predator.speed();

 

 

- interface variety는 자동으로 public / static / final이 정의되어 있음

 

 

41

Polymorphism

interface Predator {
    String getFood();

    default void printFood() {
        System.out.printf("my food is %s\n", getFood());
    }

    int LEG_COUNT = 4;  // 인터페이스 상수

    static int speed() {
        return LEG_COUNT * 30;
    }
}

interface Barkable {
    void bark();
}

interface BarkablePredator extends Predator, Barkable {
}

class Animal {
    String name;

    void setName(String name) {
        this.name = name;
    }
}

class Tiger extends Animal implements Predator, Barkable {
    public String getFood() {
        return "apple";
    }

    public void bark() {
        System.out.println("어흥");
    }
}

class Lion extends Animal 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();
    }
}

public class Sample {
    public static void main(String[] args) {
        Tiger tiger = new Tiger();
        Lion lion = new Lion();

        Bouncer bouncer = new Bouncer();
        bouncer.barkAnimal(tiger);
        bouncer.barkAnimal(lion);
    }
}

 

42

abstract class

abstract class Predator extends Animal {
    abstract String getFood();

    default void printFood() {  // default 를 제거한다.
        System.out.printf("my food is %s\n", getFood());
    }

    static int LEG_COUNT = 4;  // 추상 클래스의 상수는 static 선언이 필요하다.
    static int speed() {
        return LEG_COUNT * 30;
    }
}

(... 생략 ...)

이스는 사용 불가능하므로 삭제해야 하고 Tiger, Lion 클래스도 다음과 같이 Predator 추상클래스를 상속하도록 변경해야 한다.

abstract class Predator extends Animal {
    (... 생략 ...)
}

interface Barkable {
    (... 생략 ...)
}

interface BarkablePredator extends Predator, Barkable {
}

class Animal {
    (... 생략 ...)
}

class Tiger extends Predator implements Barkable {
    (... 생략 ...)
}

class Lion extends Predator implements Barkable {
    (... 생략 ...)
}

class ZooKeeper {
    (... 생략 ...)
}

class Bouncer {
    (... 생략 ...)
}

public class Sample {
    (... 생략 ...)
}

Predator 추상클래스에 선언된 getFood 메소드는 Tiger, Lion 클래스에 이미 구현되어 있으므로 추가할 필요는 없다. 추상클래스에 abstract로 선언된 메소드는 인터페이스의 메소드와 마찬가지로 반드시 구현해야 하는 메소드이다.

 

 
 

'Hard deck > Basic' 카테고리의 다른 글

for Projecting  (0) 2022.08.02
체(Sieve)로서 사용되는 if의 기능  (0) 2022.08.02
for 공간 내부의 시행 발생 간격  (0) 2022.08.02
boolean = (phase changer) = toggle switch  (0) 2022.08.02
002 : if PipeLine  (0) 2022.08.02