Java2 - accidentlywoo/sec GitHub Wiki

Java2 부터 정리하는 내용

  • Object 클래스
  • Class 클래스
  • String, Wrapper 클래스

Object 클래스

모든 클래스의 최상위 클래스

java.lang.Object 클래스

  • 모든 클래스는 Object클래스에서 상속 받음
  • 모든 클래스는 Object 클래스의 메서드를 사용할 수 있음
  • 모든 클래스는 Object 클래스의 일부 메서드를 재정의하여 사용할 수 있음

가지고있는 메소드들 : clone(), equals(), finalize(), getClass(), hashCode(), notify(),notifyAll(), toString(), wait(),..

class Book{
  String title;
  String author;
  public Book(String title, String author){
    this.title = title;
    this.author = author;
  }
  @Override
  public String toString(){
    return author + ","+title;
  }
}
public class ToStringTest{
  psvm(String[] args){
    Book book = new Book("토지","박경리");
    syso(book);
    String str = new String("토지");
    syso(str.toString());
  }
}

toString() 메서드의 원형

getClass().getName() + '@' + Integer.toHexString(hashCode()) 객체의 정보를 String 으로 바꾸어 사용할 때 유용함. 자바 클래스중에는 이미 정의된 클래스가 많음.

ex) String, Integer, Calendar 등

많은 클래스에서 재정의하여 사용

equals() 메서드

두 객체의 동일함을 논리적으로 재정의 할 수 있음

물리적 동일함 : 같은 주소를 가지는 객체

논리적 동일함 : 같은 학번의 학생, 같은 주문 번호의 주문

물리적으로 다른 메모리에 위치한 객체라도 논리적으로 동일한을 구하기 위한 메서드

class Student{
  int studentNum;
  String studentName;
  public Student(int studentNum, String studentName){
    this.studentNum = studentNum;
    this.studentName = studentName;
  }
  @Override
  public boolean equals(Object obj){
    if(obj instance of Student){
       Student std = (Student)obj;
       if(this.studentNum == std.studentNum)
          return true;
       else return false;
    }
  }
}
psvm(String[] args){
  String str1 = new String("abc");
  String str1 = new String("abc");
  syso(str1 == str2); // false

  Student lee = new Student(100, "Lee");
  Student lee2 = new Student(100, "Lee");
  syso(lee == lee2);
  syso(lee.equals(lee2);
}

hashCode() 메서드

hashCode() 메서드의 반환 값 : 인스턴스가 저장된 가상머신의 주소를 10진수로 반환

두 개의 서로 다른 메모리에 위치한 인스턴스가 동일하다는 것은?

  • 논리적으로 동일 : equals()의 반환값이 true

  • 동일한 hashCode 값을 가짐 : hashCode()의 반환값이 동일

Integer i1 = new Integer(100);
Integer i2 = new Integer(100);

syso(i1.equals(i2));
syso(i1.hashCode());
syso(i2.hashCode());
// equals -> true // 값, hashcodee같다.

syso(System.identityHashCode(i1));
syso(System.identityHashCode(i2));//실제 메모리 값

clone()메서드

객체의 복사본을 만듦

기본 틀(Prototype)으로 부터 같은 속성 값을 가진 객체의 복사본을 생성할 수 있음

객체지향 프로그래밍의 정보은닉에 위배되는 가능성이 있으므로 복제할 객체는 cloneable 인터페이스를 명시해야 함

class Book implements Cloneable{//mark interface
  String title;
  String author;
  public Book(String title, String author){
    this.title = title;
    this.author = author;
  }
  @Override
  public String toString(){
    return author + ","+title;
  }
  @Override
  protected Object clone() throws CloneNotSupportedException{
    return super.clone();
  }
}
public class ToStringTest{
  psvm(String[] args){
    Book book = new Book("토지","박경리");
    syso(book);
    Book book2 = book.clone();
    syso(book2);
  }
}

finalize()

가비지 콜렉터가 호출, 리소스의 해제

인스턴스가 힙메모리에 해지될때, 가비지컬렉터에 의해서 호출된다

getClass()

Class클래스와 다시 설명~

Class 클래스

자바의 모든 클래스와 인터페이스는 컴파일 후 class 파일로 생성됨

class 파일에는 객체의 정보 (멤버변수, 메서드, 생성자등)가 포함되어 있음

Class클래스는 컴파일된 class 파일에서 객체의 정보를 가져올 수 있음

// 1.
String s = new String();
Class c = s.getClass();//getClass는 Object의 메소드

// 2.
Class c = String.Class;

// 3.
Class c = Class.forName("java.lang.String"); //런타임 시점에서 바인딩 동적 로딩(<-> 컴파일 시점에서 바인딩되는 정적 로딩)

reflection 프로그래밍

Class 클래스로부터 객체의 정보를 가져와 프로그래밍 하는 방식

로컬에 객체가 없고 자료형을 알 수 없는 경우 유용한 프로그래밍

java.lang.reflect 패키지에 있는 클래스 활용

newInstance() 메소드

Class 클래스 메서드

new 키워드를 사용하지 않고 인스턴스를 생성

psvm(String[] args) throws ClassNotFoundException{
  Class c1 = String.class;

  String str = new String();
  Class c2 = str.getClass();

  Class c3 = Class.forName("java.lang.String");

  Constructor[] cons = c3.getConstructors();
  for(Constructor con : cons){
     sout(con);
  }

  Method[] methods = c3.getMethods();
  for(Method method : methods){
     syso(method);
  }
}
package classex
public class Person{
  private String name;
  private int age;
  public Person(){}
  public Person(String name){
    this.name = name;
  }
  public Person(String name, int age){
    this.name = name;
    this.age = age;
  }
  ~getter/setter
  ~toString 
}
psvm(String[] arg){
  Person person = new Person("james");
  Class c1 = Class.forName("classex.Person");
  Person person1 = (Person)c1.newInstance();
  sout(person1); // null

  Class[] parameterTypes = {String.class};
  Constructor cons = c1.getConstructor(PrameterTypes);
}
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Person person = new Person("james");
        System.out.println(person);
        //매개변수 없는 기본 생성자
        Class c1 = Class.forName("step1.Person");
        Person person1 = (Person) c1.newInstance(); //return type Object, 기본 생성자 호출
        System.out.println("Class : "+person1);
        // 매개변수가 있는 생성자
        Class[] parameterTypes= {String.class};
        Constructor cons = c1.getConstructor(parameterTypes);

        Object[] initargs = {"김유신"};
        Person person2 = (Person) cons.newInstance(initargs);
        System.out.println(person2);
    }

forName() 메소드와 동적 로딩

Class 클래스 static 메소드

동적 로딩이란? 컴파일 시에 데이터 타입이 모두 biding되어 자료형이 로딩되는 것(static loading)이 아니라 실행 중에 데이터 타입을 알고 biding되는 방식

실행 시에 로딩되므로 경우에 따라 다른 클래스가 사용될 수 있어 유용함

컴파일 타임에 체크할 수 없으므로 해당 문자열에 대한 클래스가 없는 경우 예외(ClassNotFoundException)이 발생할 수 있음

String

String은 Immutable

public final class String implements java.io.Serializable, Comparable<String>, CharSequence{
  private final char value[]; // 최초 한번 할당
}

String 클래스 선언하기

String str1 = new String("abc"); //인스턴스로 생성됨
String str2 = "abc"; // 상수풀에 있는 문자열을 가리킴

Wrapper 클래스도 똑같이 적용이 되는 내용

한번 선언되거나 생성된 문자열을 변경할 수 없음

String 클래스의 concat() 메서드 혹은 "+"를 이용하여 String을 연결하는 경우 문자열은 새로 생성됨.

StringBuilder와 StringBuffer

가변적인 char[] 배열을 멤버변수라 가지고 있는 클래스

문자열을 변경하거나 연결하는 경우 사용하면 편리한 클래스

StringBuffer는 멀티 쓰레드 프로그래밍에서 동기화(Synchronization)이 보장됨 단일 쓰레드 프로그래밍에서는 StringBuilder를 사용하는 것이 성능이 좋음

toString() 메서드로 String반환

Wrapper

primitive -> C/C++에서 넘어옴 : 이걸 쓰는 것은 객체지향에 어긋난다.라고 말하는 사람들이있다.

Python의 경우 Primitive type같은게 없음. 모든것이 객체

⚠️ **GitHub.com Fallback** ⚠️