At first glance, it may seem that the content from the beginning of the chapter up to this point is a series of rules of the Java language that programmers need to remember. But in fact, it is all a consequence of the nature of the concept: Class members belong to the class and are independent of all the instances of that class. Meanwhile, entity members are closely tied to each specific entity. All the 'rules' are a consequence of that nature.
An instance method can access instance variables simply because they belong to the same entity—the owner object to which the this reference refers. For example, the return name; statement in the getName() method in Figure 10.2 is actually return this.name; . getName() is an instance method, so it has the this reference to use for this.
A class method, on the other hand, cannot directly access an instance variable or an instance method simply because the class method does not know the owner object of the instance members. For example, when the instance variable name is accessed in the main method in Figure 10.3, Java actually understands it as this.name. But main is a class method, it is not associated with any object, so it does not have a this reference to call this.name.
All rules are derived from the nature of the concept. Therefore, we do not actually need to remember the rules once we have mastered the concept.
Maybe you are interested!
-
Java - University of Technology - 9 -
Java - University of Technology - 3 -
Java - University of Technology - 11 -
Java - University of Technology - 21 -
SQL Database Administration - Hanoi University of Business and Technology - 14
10.4. INITIALIZING CLASS VARIABLES

Static variables are initialized when the class is loaded into memory. A class is loaded when the Java virtual machine decides it is time to load it, such as when someone creates the first instance of the class, or uses a static variable or static method of the class.
There are two guarantees about the initialization of static variables: (1) static variables in a class are initialized before any objects of that class can be created; (2) static variables in a class are initialized before any static methods of that class can run;
There are two ways to initialize a static variable. First, initialize it right at the variable declaration line, for example in Figure 10.1:
private static int numOfCows = 0;
Second way: Java provides a special syntax called static initialization block – a block of code enclosed in braces { } and titled with the keyword static.
static { numOfCows = 0;
}
A class can have several static initializer blocks placed anywhere in the class definition. They are guaranteed to be invoked in the order in which they appear in the code. And
Most importantly, they are guaranteed to run before any member variables are accessed or any static methods are run.
10.5. SINGLETON DESIGN PATTERN
One application of class members is the Singleton design pattern. This pattern solves the design problem of ensuring that a class has at most one instance, such as in a system where there should be only one application window manager, a file system, or a printer spooler. Singleton classes are often used for centralized resource management and provide a single global access point to their single instance.
The Singleton pattern consists of a class that is responsible for creating its own instance. The constructor is made private to prevent creation from outside the class. A private class variable holds a reference to the single instance. The class provides a global access point to this instance through a public class method that returns a reference to the instance. Figure 10.5 illustrates the Singleton pattern in detail. Note that since the constructor cannot be accessed from outside, the getInstance() class method is the only gateway to obtaining a reference to the Singleton object. This method ensures that only one Singleton instance is created. From outside the Singleton class, whenever we want to use this Singleton instance, we only need to make a call like this:
Singleton.getInstance().doSomething();
Readers can learn more about this design pattern and its applications in the following documents:
1. Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994.
2. SingletonPattern | Object Oriented Design,
URL: http://www.oodesign.com/singleton-pattern.html
Figure 10.5: Singleton design pattern.
10.6. IMMUNE MEMBER – final
In Java, the final keyword means "cannot be changed". We can use this keyword to specify the immutability of variables, methods, and entire classes:
1. A final variable is a variable whose value cannot be modified. In other words, a final variable is a constant. We have a static final variable which is a constant of a class, a final instance variable which is a constant of an object. Local variables and parameters can also be defined as final. In the following example, 'cow' means 'female cow' so IS_FEMALE (female) is a constant with the value true for all objects of type Cow, each cow does not change color so color is a constant for each Cow object.
2. A final method is a method that cannot be overridden by a subclass.
3. A final class is a class that cannot have subclasses.
Safety is the reason for declaring final. For example, if someone were to write a subclass of String and override its methods, they could use polymorphism to use objects of the new class in code that was originally written for String. This is an undesirable situation, so String is made final to avoid this. If you need to rely on a particular implementation of a method in a class, make the class final. If you only need to fix the implementation of a few methods in a class, make those methods final, not the whole class. Of course, if a class is final, then the methods in it cannot be overridden, and you don't need to make them final.
Key points:
Class method or static method is not associated with any specific object and does not depend on any object, it is only associated with the class.
Static methods should be called from the class name.
A static method can be called without any object of that class being on the heap.
Because it is not associated with an object, a static method cannot access instance variables or instance methods.
Class variables, also known as static variables, are variables that are shared by all objects of the class. There is only one copy for the entire class, not one copy for each object.
Static methods can access static variables.
Final variables are assigned a value only once and cannot be changed.
Final methods cannot be overridden.
Final class cannot have subclass.
Exercise
1. Fill in the blank with the appropriate word
a) A variable represents information that all objects in a class share.
b) KeywordsSpecifies that a variable cannot have its value modified.
2. Are the following statements true or false?
a) To use the Math class, first create a Math object.
b) Can use static keyword for constructor
c) Static methods cannot access instance variables of the current object.
d) Static variables can be used to count the number of instances of a class.
e) Constructors are called before static variables are initialized.
f) MAX_SIZE is a good variable name for a final static variable
g) A static initialization block runs before a class's constructor is run.
h) If a class is declared with the final keyword, all its methods must also be declared final.
i) A final method can be overridden only if the class has a subclass.
j) There is no wrapper for boolean values.
k) The wrapper class is used when we want to treat a primitive value as an object.
Chapter 11. Exceptions
Program errors are common. Unusual situations also occur. Files are not found. Servers crash. An exception is a term used to describe an incorrect or unusual condition that occurs while a program is running. There are countless such situations, such as when a program divides by zero (arithmetic exception), reads a non-integer value while expecting to read an int value (number format exception), or accesses an element that is not in an array (out-of-array index exception). The possible errors and unusual conditions are endless.
No matter how well a program is designed, it is likely that errors will occur during execution. No matter how good a programmer is, we cannot control everything. In methods that are likely to fail, we need code to handle the errors if they occur.
A well-designed program should have code that protects against errors and unexpected conditions. This code should be included in the program at the early stages of development. This can help identify problems during development.
The traditional method for error prevention is to insert error detection and handling code into the program logic; use the function's return value as a means of reporting errors to the function caller. However, this method has disadvantages such as: error detection and handling code is mixed in the main algorithm, making the program more confusing, more difficult to understand, leading to more difficult to control; sometimes the return value must be used to report the calculation result of the function, so it is difficult to find a suitable value to use exclusively for reporting errors.
In Java, exception handling is a mechanism that allows these situations to be handled well. It allows possible exceptions to be resolved so that the program can continue running or terminate gracefully, helping programmers create more durable and error-tolerant programs. Compared to traditional error prevention methods, the exception mechanism makes the program run a little slower, but in return, the program structure is clearer, easier to write and easier to understand.
This chapter describes the Java exception mechanism. We will start by comparing the traditional error handling in a program with the default exception handling mechanism of Java. Next, we will present how exceptions are thrown and caught (handled) in a program, the rules that apply to different types of exceptions. Finally, we will discuss how to design and implement subclasses of Exception to serve the needs of custom exceptions.
11.1. WHAT ARE EXCEPTIONS?
11.1.1. Incident situation
First, let's take an example of a Java exception. Figure 11.1 shows a simple program that asks the user to enter two integers, calculates their quotient, and prints it on the screen.
7 7 &
I ;
" " EF
# ( 7 &
7 7 8 B 8 &
# 7 G &
7 7 8A B 8 &
# 7 G &
# &
7 7 ' 8L MB++#+L 8
&
Figure 11.1: A program without exception handling.
This program works correctly, but there is no error-handling code. If, when running the program, we enter data that is not an integer as required, the program will suddenly stop with an error message printed in the command window, for example, in Figure 11.2. This is the result of an unhandled exception.
Figure 11.2: Run-time error due to unhandled exception.
Let's take another example in Figure 11.3. Suppose we need to write a few lines of text to a file. We use the File and PrintWriter classes in the java.io package of the Java standard library, File manages files, and PrintWriter provides facilities for writing lines of text. The program simply does the following: (1) opens the file, (2) prepares it for writing, (3) writes a line of text to the file, and (4) closes the file. But when we compile it, we get
The new PrintWriter command returns an error message stating that the FileNotFoundException exception was not handled and must be caught or declared thrown.
7 7 ! &
7 79 &
2 ! @2 . (
/ J % e
9 !
( " ' " 9 ' # ( 9 ' &
! # ( ! ' &
7 &
7 &
RC f#
JC
: / ;
: / ; $ . ( < .
: / = : ( < . 4 ' ( / ( 9
> ; * 9 > ; 2 / 34
5
Figure 11.3: Compilation error due to unhandled exception.
The above two examples, and other exceptional situations, are similar in these respects.
after:
1. We call a method in a class that we did not write
2. That method may have problems running.
3. We need to know that the method can fail.
4. We need to write code to handle the incident if it occurs.
The last two points are things we haven't done yet and will discuss in the next sections.
Java methods use exceptions to tell the code that calls them, "Something unexpected happened. I ran into a problem." Java's exception handling mechanism allows us to handle the unexpected situations that occur while the program is running, allowing us to put all of our error-handling code in one easy-to-read place. It works on the principle that if we know we can expect an exception, we can prepare to deal with it when it does arise.
First, point number 3, how do we know if a method can throw an exception and what it can throw? When we get a compile error or runtime error like in the two examples above, we know some exceptions can arise. But that is not enough. We need to look for the throws declaration at the first line of the method declaration, or read the method specification to see what it says it can throw. Any method must declare all the types of exceptions it can throw.





