카테고리 없음

자바_개념_Day_28

구이제이 2024. 2. 7. 19:45

● 레이블

 

● 제네릭 : 일반화가 많이 되어있어서…

 

● 람다식




# 가장 가까운 반복문에 대해서 영향이 있다.

continue; - > 가장가까운 조건문으로 나간다.

break; -> 가장 가까운 반복문을 빠져나간다.

 

#

레이블

aa: 이런것을 레이블



ㅡㅡㅡ

 

▣ 제네릭 (Generic)  => 제네릭은 클래스 내에서 사용되는 타입을 클래스가 정의할 때가 아닌 

객체를 생성할 때 정의하겠다는 의미

- 하나의 코드를 다양한 타입의 객체에 재사용하는 객체 지향 기법

- 클래스, 인터페이스, 메서드를 정의할 때 타입을 변수로 사용

- 장점 

. 컴파일할 때 타입을 점검하기 때문에 실행 도중 발생할 오류를 미리 방지할 수 있음

. 불필요한 타입 변환이 없어 프로그램 성능이 향상된다.

 

1. 제네릭 클래스와 인터페이스

- 타입을 변수로 사용하는 클래스와 인터페이스

- <>(다이아몬드연산자) 내부에 타입 매개변수를 표시

- 타입매개변수는 객체를 생성할 때 구체적인 타입으로 대체함

- 제네릭 클래스의 타입 매개변수는 필드나 메서드의 타입

 

- 타입매개변수 : 영문대문자면 어떤 것이 사용 가능

. 일반 타입 type

. 원소(요소) E element(배열에서 많이씀)

. 키 K key

. 숫자 N number

. 값 V value 

 

- 제네릭 클래스의 생성자

제네릭클래스<적용할타입> 변수 = new 제네릭클래스<적용할타입>( );

제네릭클래스<적용할타입> 변수 = new 제네릭클래스<>( );

- 기본타입(int, long, byte, boolean,...)은 사용할 수 없고, 참조 타입만 사용 가능

>>>일반타입안되고 ‘참조타입만가능’★포장객체(wrapper클래스가 생긴것)



2. 제네릭 상속 및 타입 한정

- 자식 객체를 부모 타입 변수에 대입

- 타입 매개변수의 범위를 특정 타입으로 제한

. < T extends 특정 클래스> 반환타입 메서드명(..){  }

. < T extends 인터페이스> 반환타입 메서드명(..){  }

 

3. 제네릭 메서드

- 제네릭 메서드는 제네릭 클래스뿐만 아니라 일반 클래스의 멤버도 될 수 있다.

  - 일반 클래스에서 제네릭 메서드를 정의할 때는 타입 매개변수를 반환 타입 앞에 둠

<타입매개변수> 반환타입 메서드명(..) {  }

 

- 제네릭 메서드의 타입 매개변수는 메서드의 반환 타입이나 매개변수의 타입으로 사용할 수 있음

- 제네릭 메서드를 호출할 때는 컴파일러가 매개변수 값의 타입을 보고 구체적인 타입을 추정할 수 있어 생략 가능



=======================

▣  compareTo(Object obl)

    - 값을 비교

- 비교할 값이 매개값으로 받은 값보다 크면 : 1 을 반환

  비교할 값이 매개값으로 받은 값보다 작으면 : -1을 반환

비교할 값이 매개값과 같으면 0을 반환







최상위 부모 object

부모 animal

자식 cat

 

#(다형성) - 2가지 속성이상을 가지고 있는것, 자식,부모,형변환하는 것

object로 만든다면, object것만 쓴다(재정의 된것 제외)

그렇다면, 다시 cat을 쓰고싶다면, cat으로 형변환을 해야한다.





comparable




ㅡㅡㅡ

 

#제네릭 메소드

public class GenericMethod {

 

//일반 메소드 - 인스턴스 메소드

public void printInfo() {

System.out.println("즐거운 시간~~");

}

 

//일반 메소드 - 정적메소드(static method)

public static void printShow() {

System.out.println("안녕!! 자바");

}

//제네릭 메소드 : 메소드도 만들수도있고, 인터페이스, 클래스도 만들수있다.

//[접근제한자] static <제네릭타입> 반환타입 매소드명(매개변타입 매개변수)

 

//<T> 타입매개 변수, void : 반환되는 타입

public static <T> void showArrayContetnt(T[] arr) {

for(int i = 0 ; i < arr.length; i++) {

System.out.print(arr[i] + " ");

}

 

System.out.println();

 

 

}

 

//제네릭 메소드

//매개값으로 넘겨 받은 배열의 마지막 요소를 리턴

// 접근제한자 static 제네릭타입 반환타입 메소드명 (매개변수타입, 매개변수, ...){}

public static <T> T getLastElement(T[] lastArr) {

 

return lastArr[lastArr.length-1];

}

 

// <영문대문자 어느것 상관없음> 반환타입 : T

 

 

public static void main(String[] args) {

// GenericMethod gm = new GenericMethod(); //갹체를 여기서 생성하면 스타틱을 생성안해도된다.

 

Integer[] inArr = {10, 20, 30, 40};

Character[] chArr = {'j', 'a', 'v', 'a', ' ', 'h', 'e','l','l','o'};

String[] strArr = {"사과", "딸기", "복숭아"};

 

//#1. 메소드를 호출해서 배열의 내용을 확인

//   메소드를 호출할 때 구체적인 타입을 생략 - 컴파일러가 결정

//GenericMethod.showArrayContetnt(inArr);

// GenericMethod.showArrayContetnt(inArr);  보통은 클래스.메소드명 이다.

showArrayContetnt(inArr); //static 이라, 바로 선언할수도있다.

System.out.println();

 

showArrayContetnt(chArr); //static 이라, 바로 선언할수도있다.

System.out.println();

 

showArrayContetnt(strArr); //static 이라, 바로 선언할수도있다.

System.out.println();

 

//#2. 메소드 호출시 구체적인 타입을 명시

System.out.println("----------------------------");

GenericMethod.<Integer>showArrayContetnt(inArr);

System.out.println("----------------------------");

 

GenericMethod.<Character>showArrayContetnt(chArr);

System.out.println("----------------------------");

 

GenericMethod.<String>showArrayContetnt(strArr);

System.out.println("----------------------------");

System.out.println();

 

 

//#3. 배열의 마지막 요소를 가져와 출력

//#3-1. 구체적인 타입 생략

int num = GenericMethod.getLastElement(inArr);

System.out.println("inArr의 마지막 요소 : " + num);

System.out.println();

 

String str = GenericMethod.getLastElement(strArr);

System.out.println(str);

System.out.println();

 

//#3-2. 구체적인 타입 명시

int num1 = GenericMethod.<Integer>getLastElement(inArr);

char ch = GenericMethod.<Character>getLastElement(chArr);

System.out.println("chArr의 마지막 요소 : " + ch);

 

String st = GenericMethod.<String>getLastElement(strArr);

System.out.println("stArr의 마지막 요소 : " + st);

}

}



#제네릭 클래스

 

public class BoxGeneric<T> {

private T name;

private T kind;

 

 

public void set(T name) {

this.name = name;

}

 

public T get() {

return name;

}

 

public void show() {

System.out.println(name+ ","+ kind);

}

 

 

 

}




public class BoxGenericMain {

public static void main(String[] args) {

 

//전부 String

BoxGeneric<String> box = new BoxGeneric<>();

//위에처럼 선언한다면,

// T가 전부 String으로 바뀐다.

//내가 형변환 할필요가없다.

box.set("홍길동");

box.show();

 

//전부 Integer

BoxGeneric<Integer> boxIn = new BoxGeneric<>();

//다이아몬드연산

//

 

//전부 Cat

BoxGeneric<Cat> boxCat = new BoxGeneric<Cat>();

// 1)<cat> 2)<cat>

//두개의 1)2)의 값이 같다면, 생략해도 된다.

BoxGeneric<Cat> boxCat2 = new BoxGeneric<>();

boxCat.set(new Cat());

boxCat.show();

 

 

 

}

}