기본 클래스

손현수·2023년 3월 20일
0

Object 클래스

java.lang 패키지

  • java.lang 패키지에는 String 클래스, Integer 클래스와 같은 기본적으로 자바 프로그램에서 많이 사용하는 클래스들이 포함되어 있다.

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

  • Object 클래스는 모든 자바 클래스의 최상위 클래스이다. 모든 클래스는 Object 클래스로부터 상속을 받는다.
  • 모든 클래스가 Object 클래스를 상속받았으므로 Object의 메소드를 사용할 수 있고 재정의할 수도 있고 Object형으로 변환할 수도 있다.
  • 주로 사용되는 Object 메소드는 다음과 같다.
  • Object 메소드에는 재정의할 수 있는 메소드도 있고 그렇지 않은 메소드도 있다.

toString() 메소드

  • toString() 메소드는 객체 정보를 문자열로 바꿔준다. 예를 들어 어떤 클래스의 객체를 참조하는 변수가 book이고 book.toString()을 출력하면 클래스의 이름과 16진수 해시 코드 값이 출력된다.
  • String 클래스와 Integer 클래스는 toString() 메소드를 미리 재정의해 두었기 때문에 '클래스 이름@해시 코드'가 출력되지 않는다.
  • toString() 메소드를 필요에 맞게 재정의하면 객체의 참조 변수를 이용해 원하는 문자열을 표현할 수 있다.
class Student {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return id + ":" + name;
    }
}

public class Main {
    public static void main(String[] args) {
        Student student = new Student(20214609, "hyeonsu");

        System.out.println(student);//20214609:hyeonsu 출력
    }
}

equals() 메소드

  • equals() 메소드는 기본적으로 두 객체의 주소값을 비교하여 같으면 true, 다르면 false를 반환하는 메소드이다. 하지만 이를 재정의하면 == 기호를 사용하여 물리적으로 같은 메모리 주소인지 여부를 확인하고 equals() 메소드로는 논리적으로 같은지(메모리 주소가 다르더라도 데이터가 같은지) 확인하도록 구현할 수 있다.
class Student {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return id + ":" + name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Student) {
            Student std = (Student) obj;
            if (std.id == this.id) return true;
            else return false;
        }
        return false;
    }
}

public class Main {
    public static void main(String[] args) {
        Student student = new Student(20214609, "hyeonsu");
        Student student2 = new Student(20214609, "hyeonsu");

        System.out.println(student);
        System.out.println(student.equals(student2));
    }
}

String 클래스

String을 선언하는 두가지 방법

String str1 = new String("abc");
String str2 = "test";
  • new를 사용하여 객체를 생성하는 경우 "abc" 문자열을 위한 메모리 공간이 할당되고 새로운 객체가 생성되는 반면에 str2 = "test"와 같이 생성자를 이용하지 않고 바로 문자열 상수를 가리키는 경우에는 str2가 기존에 만들어져 있던 "test"라는 문자열 상수의 메모리 주소를 가리키게 된다. 이때 "test"는 10, 20과 같이 프로그램에서 사용되는 상수 값을 저장하는 공간인 "상수 풀"에 저장된다.

String 클래스의 final char[] 변수

  • String 클래스의 구현 내용을 보면 private final char value[]
    라고 선언된 char형 배열이 있다. final은 문자열을 변경할 수 없다는 뜻이다. 따라서 한 번 생성된 문자열은 변경되지 않는다.
public class Main {
    public static void main(String[] args) {
        String javaStr = new String("java");
        String androidStr = new String("android");

        javaStr = javaStr.concat(androidStr);
        System.out.println(javaStr);
    }
}
  • 위의 코드에서 javaStr이 참조하는 문자열이 변경된 것이고 기존에 참조하던 문자열인 "java"가 변경된 것이 아니다.

StringBuffer와 StringBuilder

  • 문자열은 변경되지 않기 때문에 String 클래스를 사용하여 문자열을 계속 연결하거나 변경하는 프로그램을 작성하면 메모리가 많이 낭비된다.
  • 이때 사용할 수 있는 것이 StringBuffer 클래스와 StringBuilder 클래스이다. 두 클래스에는 내부에 final이 아닌 변경 가능한 char[]를 변수로 가지고 있다.
  • StringBuffer 클래스는 멀티스레드에서 동시에 문자열을 변경할 때 문자열이 안전하게 변경되도록 보장하고 StringBuilder 클래스는 보장되지 않는다. 따라서 멀티스레드 프로그램이 아니라면 StringBuilder를 사용하는 것이 실행 속도가 빠르다.
public class Main {
    public static void main(String[] args) {
        String javaStr = new String("java");

        StringBuilder buffer = new StringBuilder(javaStr);

        buffer.append(" and");
        buffer.append(" android");
        buffer.append(" programming is fun!");
        
        System.out.println(buffer);
    }
}

Wrapper 클래스

Integer 클래스

Integer iValue = new Integer(100);
int myValue = iValue.intValue();//int 값 가져오기

Integer number1 = Integer.valueOf("100");
Integer number2 = Interger.valueOf(100);

int num = Integer.parseInt("100");//문자열이 어떤 숫자를 나타낼 때 문자열을 int로 반환할 수 있다.
profile
안녕하세요.

0개의 댓글