hyunjungkimm / godofjava_2024

0 stars 0 forks source link

# java #3

Open hyunjungkimm opened 1 week ago

hyunjungkimm commented 1 week ago

클래스

캡슐화(Encapsulation)

객체(Object)

변수의 종료

public class VariableTypes {
  int instanceVariable; 
  static int classVariable;
  public void method(int parameter) {
    int localVariable;
  }
}

Overriding, Overloading의 차이점

Overriding

Overloading

상속

생성자

메소드

변수

형변환

다형성(Polymorphism)

java.lang.Object 클래스

hyunjungkimm commented 1 week ago

인터페이스와 추상클래스, enum

사용 이유

인터페이스

abstract 클래스

abstract 클래스 존재 이유

final

클래스

메소드

변수

참조 자료형

package chapter13;

import chapter12.MemberDTO;

public class FinalReferenceType {
    final MemberDTO dto = new MemberDTO();

    public static void main(String[] args) {
       FinalReferenceType finalReferenceType = new FinalReferenceType();
       finalReferenceType.checkDTO();
    }

    public void checkDTO() {
        System.out.println(dto);
        //기본자료형과 마찬가지로 참조 자료형도 두 번 이상 할당하거나 새로 생성자를 사용하여 초기화할 수 없음
        //dto = new MemberDTO();
        dto.name = "Sangmin";
        System.out.println(dto);
    }
}

enum 클래스

hyunjungkimm commented 6 days ago

예외

try ~ catch 구문

try { 
//예외가 발생 가능한 문장
} catch(예외1 e1) {
//예외1이 발생했을 때 처리 문장
} catch(예외2 e2) {
//예외2가 발생했을 때 처리 문장
} finally {
// try나 catch가 어떻게 수행되었든 간에 수행되는 문장
}

자바에서 사용하는 예외의 종류

image

throw와 throws

java.lang.Throwable 클래스

hyunjungkimm commented 5 days ago

String

image

== 비교가 아닌 equals() 메소드로 비교

getBytes() 메소드

객체의 널 체크

메소드

String, StringBuffer, StringBuilder클래스

String

hyunjungkimm commented 5 days ago

Nested class

import java.util.EventListener;

public class NestedValueReference { public int publicInt = 0; protected int protectedInt = 1; int justInt = 2; private int privateInt = 3; static int staticInt = 4;

//staticNested 클래스 - static 변수만 참조 가능
static class StaticNested {
    public void setValue() {
        //static으로 선언되어 있어서 부모 클래스에 static하지 않은 변수 참조 불가능
        staticInt = 14;
    }
}

//내부 클래스- 감싸고 있는 클래스의 어떤 변수라도 참조 가능
class Inner {
    public void setValue() {
        publicInt = 20;
        protectedInt = 21;
        justInt = 22;
        privateInt = 23;
        staticInt = 24;
    }
}
//익명 클래스 - 감싸고 있는 클래스의 어떤 변수라도 참조 가능
public void setValue() {
    EventListener listener = new EventListener() {
        public void onClick() {
            publicInt = 30;
            protectedInt = 31;
            justInt = 32;
            privateInt = 33;
            staticInt = 34;
        }
    };
}

}

public class ReferenceAtNested { static class StaticNested { private int staticNested = 99; }

class Inner {
    private int inner = 100;
}
// 클래스의 객체 생성한 후 그 값을 참조하는 것은 가능함
//private이어도 접근 가능
public void setValue(int value) {
    ReferenceAtNested.StaticNested nested = new ReferenceAtNested.StaticNested();
    nested.staticNested = value;
    Inner inner = new Inner();
    inner.inner = value;
}

}


## 1. Static nested class 
- 클래스 선언할 때 static으로 선언함 
- 한 곳에서만 사용되는 클래스를 논리적으로 묶어서 처리할 필요가 있을 때
## 2. inner(내부) class
- 클래스 선언할 때 static 없이 선언함
- 캡슐화(하나의 클래스에서 어떤 공통적인 작업을 수행하는 클래스가 필요한데 다른 클래스에서는 그 클래스가 전혀 필요가 없을 때 이럴때 내부 클래스를 만들어 사용한다.)가 필요할때, 내부 구현을 감추고 싶을때 
- 다른 곳에서 재사용할 일이 없을때 만들어야 함 
### 2-1. Local inner class 
### 2-2. Anonymous inner(내부 익명) class
- 이름이 없는 클래스
- 다른 클래스나 메소드에서는 참조할 수 없다. 
hyunjungkimm commented 5 days ago

어노테이션

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface UseAnnotation { int number(); String text() default "first annotation"; }

public class UserAnnotationSample { @UseAnnotation(number = 0) public static void main(String[] args) { UserAnnotationSample sample = new UserAnnotationSample(); }

@UseAnnotation(number = 1)
public void annotationSample1(){

}
@UseAnnotation(number = 2, text = "second")
public void annotationSample2(){

}
@UseAnnotation(number = 3, text = "third")
public void annotationSample3(){

}

}

import java.lang.reflect.Method;

public class UserAnnotationCheck { public static void main(String[] args) { UserAnnotationCheck sample = new UserAnnotationCheck(); sample.checkAnnotations(UserAnnotationSample.class); }

private void checkAnnotations(Class useClass) {
    Method[] methods = useClass.getDeclaredMethods();
    for(Method method : methods) {
        UseAnnotation annotation = method.getAnnotation(UseAnnotation.class);
        if(annotation != null) {
            int number = annotation.number();
            String text =  annotation.text();

            System.out.printf("""
                        %s () : number = %d, text = %s
                    """, method.getName(), number, text);
        }else {
            System.out.printf("""
                        %s () : annotation is null
                    """, method.getName());
        }
    }
}

} /* main () : number = 0, text = first annotation annotationSample1 () : number = 1, text = first annotation annotationSample2 () : number = 2, text = second annotationSample3 () : number = 3, text = third