물체 수업이 있습니다 java.lang 패키지. Java의 모든 클래스는 직접 또는 간접적으로 파생됩니다. 물체 수업. 클래스가 다른 클래스를 확장하지 않는 경우 해당 클래스는 다음 클래스의 직계 자식 클래스입니다. 물체 다른 클래스를 확장하면 간접적으로 파생됩니다. 따라서 Object 클래스 메소드는 모든 Java 클래스에서 사용할 수 있습니다. 따라서 객체 클래스는 모든 Java 프로그램에서 상속 계층의 루트 역할을 합니다.

객체 클래스 메서드 사용
Object 클래스는 다음과 같은 여러 메서드를 제공합니다.
- toString() 메서드
- hashCode() 메서드
- 같음(Object obj) 메서드
- finalize() 메소드
- getClass() 메소드
- 클론() 메서드
- wait(), inform() informAll() 메소드
1. toString() 메소드
toString()은 객체의 문자열 표현을 제공하며 객체를 문자열로 변환하는 데 사용됩니다. Object 클래스의 기본 toString() 메소드는 객체가 인스턴스인 클래스 이름, 기호 문자 `@' 및 객체 해시 코드의 부호 없는 16진수 표현으로 구성된 문자열을 반환합니다. 즉, 다음과 같이 정의됩니다.
// Default behavior of toString() is to print class name, then // @, then unsigned hexadecimal representation of the hash code // of the object public String toString() { return getClass().getName() + '@' + Integer.toHexString(hashCode()); }> 항상 toString() Object의 자체 문자열 표현을 가져오는 메서드입니다. toString() 메서드 재정의에 대한 자세한 내용은 다음을 참조하세요. Java에서 toString() 재정의
메모: 객체 참조를 인쇄하려고 할 때마다 내부적으로 toString() 메서드가 호출됩니다.
Student s = new Student(); // Below two statements are equivalent System.out.println(s); System.out.println(s.toString());>
2. hashCode() 메소드
모든 객체에 대해 JVM은 해시코드인 고유 번호를 생성합니다. 고유한 개체에 대해 고유한 정수를 반환합니다. 이 메서드에 대한 일반적인 오해는 hashCode() 메서드가 올바르지 않은 개체의 주소를 반환한다는 것입니다. 알고리즘을 사용하여 객체의 내부 주소를 정수로 변환합니다. hashCode() 메소드는 다음과 같습니다. 토종의 Java에서는 객체의 주소를 찾는 것이 불가능하기 때문에 C/C++와 같은 기본 언어를 사용하여 객체의 주소를 찾습니다.
hashCode() 메소드 사용
컬렉션의 개체를 검색하는 데 사용되는 해시 값을 반환합니다. JVM(Java Virtual Machine)은 객체를 HashSet, HashMap, Hashtable 등과 같은 해싱 관련 데이터 구조로 저장하면서 해시코드 방식을 사용합니다. 해시코드 기반으로 객체를 저장하는 가장 큰 장점은 검색이 쉽다는 것입니다.
자바 브레이크
메모: 재정의 해시 코드() 모든 개체에 대해 고유한 번호를 생성하도록 메서드를 수행해야 합니다. 예를 들어 학생 수업의 경우 롤 번호를 반환할 수 있습니다. hashCode() 메서드에서 학생의 고유한 정보를 얻을 수 있습니다.
자바
// Java program to demonstrate working of> // hashCode() and toString()> public> class> Student {> >static> int> last_roll =>100>;> >int> roll_no;> >// Constructor> >Student()> >{> >roll_no = last_roll;> >last_roll++;> >}> >// Overriding hashCode()> >@Override> public> int> hashCode() {>return> roll_no; }> >// Driver code> >public> static> void> main(String args[])> >{> >Student s =>new> Student();> >// Below two statements are equivalent> >System.out.println(s);> >System.out.println(s.toString());> >}> }> |
>
>
출력 :
Student@64 Student@64>
4*16에 유의하세요.0+ 6*161= 100
문자열과 부분 문자열
3. equals(Object obj) 메소드
주어진 객체를 이 객체(메소드가 호출되는 객체)와 비교합니다. 이는 객체가 동일한지 비교하는 일반적인 방법을 제공합니다. 재정의하는 것이 좋습니다. 같음(객체 obj) 객체에 대한 우리 자신의 동등 조건을 얻는 방법입니다. equals(Object obj) 메서드 재정의에 대한 자세한 내용은 다음을 참조하세요. Java에서 같음 메소드 재정의
메모: 일반적으로 해시 코드() 이 메소드가 재정의될 때마다 동일한 객체는 동일한 해시 코드를 가져야 한다는 hashCode 메소드의 일반 계약을 유지하기 위해 메소드를 사용합니다.
4. getClass() 메소드
이 개체의 클래스 개체를 반환하고 개체의 실제 런타임 클래스를 가져오는 데 사용됩니다. 이 클래스의 메타데이터를 가져오는 데에도 사용할 수 있습니다. 반환된 Class 객체는 표현된 클래스의 정적 동기화 메서드에 의해 잠긴 객체입니다. 최종이므로 재정의하지 않습니다.
자바
// Java program to demonstrate working of getClass()> public> class> Test {> >public> static> void> main(String[] args)> >{> >Object obj =>new> String(>'GeeksForGeeks'>);> >Class c = obj.getClass();> >System.out.println(>'Class of Object obj is : '> >+ c.getName());> >}> }> |
>
>
산출:
Class of Object obj is : java.lang.String>
메모: .class 파일을 로드한 후 JVM은 다음 유형의 객체를 생성합니다. java.lang.Class 힙 영역에 있습니다. 이 클래스 객체를 사용하여 클래스 수준 정보를 얻을 수 있습니다. 그것은 널리 사용됩니다 반사
5. finalize() 메소드
이 메소드는 객체가 가비지 수집되기 직전에 호출됩니다. 그것은 가비지 컬렉터 가비지 수집기가 개체에 대한 참조가 더 이상 없다고 판단하면 개체에 대한 참조가 없습니다. 시스템 자원을 폐기하고 정리 작업을 수행하며 메모리 누수를 최소화하려면 finalize() 메서드를 재정의해야 합니다. 예를 들어, 서블릿 개체 웹 컨테이너를 삭제하기 전에 항상 finalize 메서드를 호출하여 세션 정리 작업을 수행합니다.
메모: finalize 메소드는 그냥 호출됩니다. 한 번 해당 객체가 여러 번 가비지 수집에 적합하더라도 객체에 대해.
자바
10억은 몇 백만인가요?
// Java program to demonstrate working of finalize()> public> class> Test {> >public> static> void> main(String[] args)> >{> >Test t =>new> Test();> >System.out.println(t.hashCode());> >t =>null>;> >// calling garbage collector> >System.gc();> >System.out.println(>'end'>);> >}> >@Override> protected> void> finalize()> >{> >System.out.println(>'finalize method called'>);> >}> }> |
>
>
산출:
1510467688 finalize method called end>
6. 클론() 메소드
이 객체와 정확히 동일한 새 객체를 반환합니다. clone() 메소드는 다음을 참조하세요. 복제() .
나머지 세 가지 방법 기다리다() , 통지() 통지모두() 동시성과 관련이 있습니다. 인용하다 Java의 스레드 간 통신 자세한 내용은.
Java의 모든 Object 클래스 메소드를 사용하는 예
xor cpp
자바
import> java.io.*;> public> class> Book>implements> Cloneable {> >private> String title;> >private> String author;> >private> int> year;> >public> Book(String title, String author,>int> year)> >{> >this>.title = title;> >this>.author = author;> >this>.year = year;> >}> >// Override the toString method> >@Override> public> String toString()> >{> >return> title +>' by '> + author +>' ('> + year +>')'>;> >}> >// Override the equals method> >@Override> public> boolean> equals(Object obj)> >{> >if> (obj ==>null> || !(obj>instanceof> Book)) {> >return> false>;> >}> >Book other = (Book)obj;> >return> this>.title.equals(other.getTitle())> >&&>this>.author.equals(other.getAuthor())> >&&>this>.year == other.getYear();> >}> >// Override the hashCode method> >@Override> public> int> hashCode()> >{> >int> result =>17>;> >result =>31> * result + title.hashCode();> >result =>31> * result + author.hashCode();> >result =>31> * result + year;> >return> result;> >}> >// Override the clone method> >@Override> public> Book clone()> >{> >try> {> >return> (Book)>super>.clone();> >}> >catch> (CloneNotSupportedException e) {> >throw> new> AssertionError();> >}> >}> >// Override the finalize method> >@Override> protected> void> finalize()>throws> Throwable> >{> >System.out.println(>'Finalizing '> +>this>);> >}> >public> String getTitle() {>return> title; }> >public> String getAuthor() {>return> author; }> >public> int> getYear() {>return> year; }> >public> static> void> main(String[] args)> >{> >// Create a Book object and print its details> >Book book1 =>new> Book(> >'The Hitchhiker's Guide to the Galaxy'>,> >'Douglas Adams'>,>1979>);> >System.out.println(book1);> >// Create a clone of the Book object and print its> >// details> >Book book2 = book1.clone();> >System.out.println(book2);> >// Check if the two objects are equal> >System.out.println(>'book1 equals book2: '> >+ book1.equals(book2));> >// Get the hash code of the two objects> >System.out.println(>'book1 hash code: '> >+ book1.hashCode());> >System.out.println(>'book2 hash code: '> >+ book2.hashCode());> >// Set book1 to null to trigger garbage collection> >// and finalize method> >book1 =>null>;> >System.gc();> >}> }> |
>
>산출
The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979) The Hitchhiker's Guide to the Galaxy by Douglas Adams (1979) book1 equals book2: true book1 hash code: 1840214527 book2 hash code: 1840214527>