코딩배움일지/JAVA
Java 12일차 2(빌더)
karatejin
2022. 11. 25. 11:23
static 은 static 끼리 호출 가능
import lombok.AllArgsConstructor;
import lombok.ToString;
@ToString
@AllArgsConstructor /*빌더 안쓰고 만든것*/
public class Student {
private int studentCode;
private String name;
private String address;
public static StudentBuilder builder(){ /*스테틱으로 했으면 다른것도 스테틱*/
return new StudentBuilder(); /*객체 주소 생김. Student 아니고 StudentBuilder*/
}
/*public class StudenmtBuilder라면 return new Student().new StudentBuilder();= 이렇게 해야하는데 메모리 낭비. 빠잉 안써 */
public static class StudentBuilder{ /* 내부 클래스 InnerClass */
private int studentCode; /*내부클래스는 바깥 클래스와 같이 세팅*/
private String name;
private String address;
public StudentBuilder studentCode(int studentCode){ /*변수명과 메서드 일치하게 매개변수까지 일치*/
this.studentCode = studentCode;
return this; /*자기 자신의 주소를 리턴 */
}
public StudentBuilder name(String name){ /*변수명과 메서드 일치하게 매개변수까지 일치*/
this.name = name;
return this; /*자기 자신의 주소를 리턴 */
}
public StudentBuilder address(String address){ /*변수명과 메서드 일치하게 매개변수까지 일치*/
this.address = address;
return this; /*자기 자신의 주소를 리턴 */
}
public Student build(){
return new Student(studentCode, name, address);/*빌더 안에 있는것*/
}
}
}
클래스 안의 클래스 : 내부클래스(외부클래스 객체가 생성되어야만 내부클래스 생성할수 있다?
public class StudentMain {
public static void main(String[] args) {
Student student = Student.builder()
.studentCode(20220001)
.name("양진구")
.address("김해시 삼계로223")
.build();
System.out.println(student);
Student.StudentBuilder sb = new Student.StudentBuilder(); /*StudentBuilder 의 생성*/
}
}
제네릭(generic)이란?
자바에서 제네릭(generic)이란 데이터의 타입(data type)을 일반화한다(generalize)는 것을 의미합니다.
제네릭은 클래스나 메소드에서 사용할 내부 데이터 타입을 컴파일 시에 미리 지정하는 방법입니다.
이렇게 컴파일 시에 미리 타입 검사(type check)를 수행하면 다음과 같은 장점을 가집니다.
1. 클래스나 메소드 내부에서 사용되는 객체의 타입 안정성을 높일 수 있습니다
2. 반환값에 대한 타입 변환 및 타입 검사에 들어가는 노력을 줄일 수 있습니다.
제네릭의 선언 및 생성
자바에서 제네릭은 클래스와 메소드에만 다음과 같은 방법으로 선언할 수 있습니다.
class MyArray<T> { /*일반자료형은 못들어 온다.*/ /*참조자료형만*/
T element; /*자료형 대신 T*/
void setElement(T element) { this.element = element; }
T getElement() { return element; } /*반환 자료형*/
}
import lombok.Getter;
public class Information<T> {
@Getter
private T target; /*T 는 오브젝트. 제네릭을 쓰면 다운 캐스팅을 할 필요 ㄴㄴ*/
public Information(T target) {
this.target = target;
}
public void printInfo(){
System.out.println(target);
}
}
import lombok.Getter;
public class Information2<T> {
@Getter
private Object target;
public Information2(Object target) {
this.target = target;
}
public void printInfo(){
System.out.println(target);
}
}
public class InformationMain {
public static void main(String[] args) {
Student student = Student.builder()
.studentCode(20220001)
.name("박준현")
.build();
Teacher teacher = Teacher.builder()
.teacherCode(200)
.name("김준일")
.build();
Information<Student> studentInformation /*<Student> 없다면 클래스를 더 만들어야 한다.*/
= new Information<Student>(student); /*<Student>넣으면 T자리에 <Student>간 들어간다.*/
Information<Teacher> teacherInformation
= new Information<Teacher>(teacher);
Information2 i1 = new Information2(student);
Information2 i2 = new Information2(teacher);
studentInformation.printInfo();
teacherInformation.printInfo();
System.out.println("학생이름: " + studentInformation.getTarget().getName()); /*getTarget() = student*/
System.out.println("학생이름2: " + ((Student)i1.getTarget()).getName()); /*Student로 다운캐스팅 해줘야 됨 Object 니까*/
}
}