Home Java javaTutorial The role and usage of Object class in java

The role and usage of Object class in java

Jun 26, 2017 am 11:25 AM
object abnormal

Methods of Object class
String roString() returns the string representation type of the object + @ + hash value (address value)
You can only distinguish the address value of an object It doesn't make much sense whether they are the same object, so subclasses will generally override this method to no longer print the address value but the attribute


The shortcut key for overriding the toString method is alt + shift + s + s

Operators like * cannot operate on reference data types
, but == can operate on reference data types. At any time, as long as == compares reference data types, the address value will always be compared.
public boolean equals(Object obj) returns a boolean type to compare whether two objects are equal. What is compared is the address value.
Subclasses can override this method to compare the attribute values ​​of two objects.

The difference between exceptions and errors
Exceptions can be handled, and the code can continue to execute after handling
Errors cannot be handled, and you can only modify the code, otherwise the program cannot be executed

The first exception handling The way to declare exceptions
The throw keyword is used in the method
throw exception object
The throws keyword is used in the declaration of the method to declare the exception
throws The class name of the exception
Note Matters:
1. throws can declare multiple exceptions, separated by commas
2. throws can declare the common parent class of multiple exceptions

The first exception Two processing methods

try{
  可能出现异常的代码
}catch(异常类名  变量名){
  任意内容 一般打印异常对象的信息
}
Copy after login

Multi-catch exception handling

try{  可能出现异常的代码}catch(异常的类名 变量名){
}catch(){
}...
Copy after login

Notes:
Is there any order between multiple catches?
If there is no direct inheritance relationship between exceptions, there is no order
ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException extends RuntimeException
NullPointerException extends RuntimeException
If there is an inheritance relationship between exceptions, there is an order, and the larger ones are placed later
NullPointerException extends RuntimeException

If the parent class exception is caught, the subclass exception can be omitted (not captured) because of the polymorphic call

finally
try{
  }catch(){
  }finally{
    必须执行的代码 
    无论是否有异常 无论是否处理了异常 
  }
Copy after login


Compile-time exception The difference from runtime exception
Compile-time exception Exception
An error is reported during compilation and must be handled. The program cannot be executed without handling it
Runtime exception RuntimeException
No error will be reported during compilation. Error will be reported when running. It can be processed or not processed. Runtime exception is not recommended.
Generally, runtime exception occurs because there is a problem with the code and the code needs to be modified
The program will be interrupted when a runtime exception is thrown, so we sometimes use runtime exceptions to help us interrupt the program


Exception issues overriding child and parent class methods
If the parent class method throws an exception
The subclass does not need to throw an exception
The subclass can also throw an exception, but the exception thrown by the subclass must be less than or equal to the exception thrown by the parent class
If the parent class method does not throw an exception
Subclasses cannot throw exceptions. If there are exceptions in the subclass, they can only handle them themselves and cannot throw them.


Three commonly used methods for exceptions
Get Exception information method
String getMessage() "File not found"
String toString() java.io.FileNotFoundException: File not found
void printStackTrace() The most detailed exception information Exception class name string Location, etc.

Custom exception
Inheriting Exception is a compile-time exception. Inheriting RuntimeException is a run-time exception
Add a constructor

 1     public class NoAgeException extends Exception{ 2  3     public NoAgeException(){ 4          5     } 6      7     public NoAgeException(String message){ 8 //        System.out.println(message); 9         super(message);10     }11 }
Copy after login

========================================== ===============

 1 public class NoAgeException extends RuntimeException{ 2  3     public NoAgeException(){ 4          5     } 6      7     public NoAgeException(String message){ 8 //        System.out.println(message); 9         super(message);10     }11 }
Copy after login

Use of custom exceptions
How to use custom exceptions for the exceptions provided by JDK
Handling of custom exceptions
Either throws or try catch

The above is the detailed content of The role and usage of Object class in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the common causes of OutOfMemoryError exceptions in Java? What are the common causes of OutOfMemoryError exceptions in Java? Jun 25, 2023 pm 08:43 PM

Java is one of the most widely used programming languages, but when developing applications using Java, it is easy to encounter "OutOfMemoryError" exception errors, which often bring some challenges to developers. What exactly causes the OutOfMemoryError exception in Java? Next, let’s take a closer look. Memory Leak (MemoryLeak) Memory leak refers to when an object cannot be recycled by the garbage collector, it will cause a memory leak.

How to solve Java thread interrupt timeout exception (ThreadInterruptedTimeoutExceotion) How to solve Java thread interrupt timeout exception (ThreadInterruptedTimeoutExceotion) Aug 18, 2023 pm 01:57 PM

How to solve the Java thread interrupt timeout exception (ThreadInterruptedTimeoutException). In Java multi-thread programming, we often encounter situations where the thread execution time is too long. In order to prevent threads from occupying too many system resources, we usually set a timeout. When the thread execution time exceeds the timeout, we hope to be able to interrupt the execution of the thread. Java provides a thread interruption mechanism. By calling the thread's interrupt() method, you can

Methods to solve Java reflection exception (ReflectiveOperationException) Methods to solve Java reflection exception (ReflectiveOperationException) Aug 26, 2023 am 09:55 AM

Methods to solve Java reflection exceptions (ReflectiveOperationException) In Java development, reflection (Reflection) is a powerful mechanism that allows programs to dynamically obtain and operate classes, objects, methods, properties, etc. at runtime. Through reflection, we can implement some flexible functions, such as dynamically creating objects, calling private methods, obtaining class annotations, etc. However, using reflection also brings some potential risks and problems, one of which is reflection anomalies (

A guide to the unusual missions in the Rise of Ronin Pool A guide to the unusual missions in the Rise of Ronin Pool Mar 26, 2024 pm 08:06 PM

The abnormality in the pool is a side task in the game. Many players want to know how to complete the abnormality in the pool task. It is actually very simple. First, we must master the technique of shooting in the water before we can accept the task and investigate the source of the stench. Later, we discovered It turns out that there are a lot of corpses under the pool. Let’s take a look at this graphic guide for the unusual tasks in the pool in Rise of Ronin. Guide to unusual missions in the Ronin Rise Pool: 1. Talk to Iizuka and learn the technique of shooting in the water. 2. Go to the location in the picture below to receive the abnormal task in the pool. 3. Go to the mission location and talk to the NPC, and learn that there is a foul smell in the nearby pool. 4. Go to the pool to investigate. 5. Swim to the location in the picture below, dive underwater, and you will find a lot of corpses. 6. Use a camera to take pictures of the corpse. 7

Practical tips for efficiently solving Java large file reading exceptions Practical tips for efficiently solving Java large file reading exceptions Feb 21, 2024 am 10:54 AM

Practical tips for efficiently resolving large file read exceptions in Java require specific code examples. Overview: When processing large files, Java may face problems such as memory overflow and performance degradation. This article will introduce several practical techniques to effectively solve Java large file reading exceptions, and provide specific code examples. Background: When processing large files, we may need to read the file contents into memory for processing, such as searching, analyzing, extracting and other operations. However, when the file is large, the following problems are often encountered: Memory overflow: trying to copy the entire file at once

MIT's latest masterpiece: using GPT-3.5 to solve the problem of time series anomaly detection MIT's latest masterpiece: using GPT-3.5 to solve the problem of time series anomaly detection Jun 08, 2024 pm 06:09 PM

Today I would like to introduce to you an article published by MIT last week, using GPT-3.5-turbo to solve the problem of time series anomaly detection, and initially verifying the effectiveness of LLM in time series anomaly detection. There is no finetune in the whole process, and GPT-3.5-turbo is used directly for anomaly detection. The core of this article is how to convert time series into input that can be recognized by GPT-3.5-turbo, and how to design prompts or pipelines to let LLM solve the anomaly detection task. Let me introduce this work to you in detail. Image paper title: Largelanguagemodelscanbezero-shotanomalydete

C++ function exceptions and single testing: ensuring code soundness C++ function exceptions and single testing: ensuring code soundness May 03, 2024 am 09:18 AM

Exception handling and unit testing are important practices to ensure the soundness of C++ code. Exceptions are handled through try-catch blocks, and when the code throws an exception, it jumps to the catch block. Unit testing isolates code testing to verify that exception handling works as expected under different circumstances. Practical case: The sumArray function calculates the sum of array elements and throws an exception to handle an empty input array. Unit testing verifies the expected behavior of a function under abnormal circumstances, such as throwing an std::invalid_argument exception when an array is empty. Conclusion: By leveraging exception handling and unit testing, we can handle exceptions, prevent code from crashing, and ensure that the code behaves as expected under abnormal conditions.

How to solve Java network connection reset exception (ConnectionResetException) How to solve Java network connection reset exception (ConnectionResetException) Aug 26, 2023 pm 07:57 PM

How to solve the Java network connection reset exception (ConnectionResetException) When doing Java network programming, you often encounter the network connection reset exception (ConnectionResetException). This exception means that after the connection is established, the other host accidentally closed the connection. This may be caused by a crash of the other party's host, network interruption, or firewall configuration. When writing network applications, we need to handle this exception to ensure that the program can run normally

See all articles