java study notes (day 4)

Inheritance can be understood as an "is-a" relationship in the real world. Inheritance is achieved by specifying its parent class when declaring a class through the extends keyword: [modifier] class class name extends parent class name

Inheriting a parent class to produce a new subclass not only has the variables and methods of the parent class, but also can add new member variables and member methods to the subclass to enhance the function of the parent class, which is the so-called extension. Define multiple overloaded methods for a method of the parent class in the subclass to increase the flexibility of the class.

A subclass can override a method of the parent class or override a method of the parent class. Just define the same methods in the subclass as in the parent class. You can also use the super keyword to refer to the method of the parent class, and then add new business code. You can also use the super keyword in the constructor of the subclass to execute the constructor of the parent class: super([construction parameter list])

Java defines private, public, protected, and default permission modifiers that control access rules to classes and class member variables and member methods. In addition, the static and final keywords can be assisted to define special rules.

Modifiers in Java Language
access package location kind build decoration symbol
modifier private protected default modifier public
this class visible visible visible visible
Other classes in the same package Invisible visible visible visible
classes from other packages Invisible Invisible Invisible visible
subclass of the same package Invisible visible visible visible
Subclasses from other packages Invisible visible Invisible visible

Classes, member variables and member methods modified with public can be accessed by other classes, including any class in any package and subclasses.

Private is a private permission modifier, which can only be accessed by this class, and will deny access in other ways.

protected is a protection-level permission modifier that protects the member from being accessed by other packages or non-subclasses.

When no permission modifier is added, the compiler will use the default modifier, whose permission level is similar to protected, except that subclasses defined by other packages cannot access the members of the parent class's default permission modifier.

Encapsulation refers to hiding the properties of an object inside the object, and does not allow direct access and modification from the outside. Setters and accessors in the Java specification are standard methods of implementing encapsulation, which are used to get and set the property values ​​of an object.

To achieve encapsulation, the first step is to set the member variables of the class (that is, the properties of the object) to use the private modifier, so that other classes cannot directly access the member variables, so as to prevent external direct access and modification. After a member variable is set to private, other classes cannot access it, and the value of the member variable must be set and modified through the setter method defined in this class. The names of setter methods are generally prefixed with set and suffixed with the property name. For the setter, it needs to be exposed to other classes to make it accessible, so the public modifier is used. In the method body to distinguish between parameters and member variables, the this keyword is used to refer to member variables and assign values ​​to the parameters, or parameters with different names from member variables can be used. To use accessor methods to read property values ​​of an object. Accessors prefix method names with get or is and suffix with property names. For properties of type boolean, accessor methods should be defined with the is prefix.

Press "Shift+Alt+S", R shortcut key in Eclipse, and the "Generate Getter and Setter" dialog box will pop up. This dialog box is the wizard for generating accessors and setters.

In Java, all classes directly or indirectly inherit the java.lang.Object class. The Object class is a special class, it is the parent class of all classes, that is to say, any class in the Java language is a subclass of the Object class. When creating a class, if you do not use the extends keyword to inherit the specified class, the compiler always inherits the Object class directly by default. If you specify another class to inherit, it will also inherit the Object class indirectly.

The Object class mainly includes methods such as clone(), finalize(), equals(), and toString(). Among them, two commonly used methods are equals() and toString() methods. Since all classes are subclasses of the Object class, any class can override the methods in the Object class.

Note: The getClass(), notify(), notifyAll(), wait() and other methods in the Object class cannot be overridden because these methods are defined as final types.

The equals() method is defined in the Object class to determine whether two objects are the same method. Most subclasses override this method to compare objects of a specified type. If the subclass of Object does not override the equals() method, this method will use the "==" operator to judge the two objects by default.

The function of the toString() method in the Object class is to convert an object into a string form. When an object participates in the "+" connector operation of a string, this method is also called to convert the object from a string, and then with Another string operand concatenation. The toString() method returns a String() instance. In practical applications, the toString() method is usually overridden to provide a specific output mode for the object. When this class is converted to or concatenated with a string, the overridden toString() method will be called automatically.

When performing type conversion, if the object is converted to the wrong type, a ClassCastException will occur, so it is necessary to judge the type of the object before performing type conversion to prevent program errors. Java uses the instanceof operator to complete the judgment of the object type. The instanceof operator can be used to determine whether the object is an instance object of the specified class or subclass, or the implementation class object of the interface: obj instanceof Class; the return value is a boolean value, true or false. An object is an instance of the class that was created for the object, as well as an instance of the parent class. So they can cast to the parent's type or assign the child's object to the parent's object variable. This form of assigning a subclass object to a parent class reference is called upcasting, and it will cause the declared object to only call methods of the parent class. Because there is no new method of the child class defined in the parent class, it only contains the method when the parent class is defined.

Any object is judged using the instanceOf keyword and the Object class, and the returned result must be true. Objects of unknown types can be passed using variables of type Object. After judging the type of the object, use forced type conversion to convert the object to the original type, and then the required method can be called. This form of converting a parent class object to a subclass object is called downcasting. Downcasting must first determine whether the type of the object has an inheritance relationship with the type to be converted, otherwise an error will occur.

Polymorphism means that the same operation in a program has different semantic interpretations in different environments. Upcasting can declare a reference variable of the parent class, but assign it to an instance object of the child class. That is, the declaration and assignment of an object variable may not be of the same type. By using a reference to the parent class type, you can define polymorphic arrays or polymorphic methods, etc.

A polymorphic array is that the array is declared using the parent class, and the elements in the array are all instance objects of the subclass. They have methods with the same name as the parent class, but the method bodies can be different.

Method parameters can also be polymorphic, and method return types can also be polymorphic.

Abstract classes in Java language cannot instantiate objects.

A class defined using the abstract keyword is called an abstract class, and a method defined using this keyword is called an abstract method. An abstract method has no method body. Abstract classes must be inherited, in fact abstract classes have no meaning other than being inherited. If you declare an abstract method, you must define the class that carries the abstract method as abstract. It is impossible to define an abstract method in a non-abstract class, that is, as long as there is an abstract method in the class, this class must be marked as abstract. After the abstract class is inherited, all abstract methods in the abstract class must be rewritten, and the method body must be defined, otherwise the compilation will fail.

The java language stipulates that a class cannot inherit multiple parent classes at the same time, that is, java only supports single inheritance.

An interface is an extension of an abstract class, it can be seen as a pure abstract class, all methods in an interface have no method body. Interfaces are defined using the interface keyword. A class that implements an interface can use the implements keyword.

The method defined in the interface must be defined as public or abstract modifier, other modification permissions are not recognized by the Java compiler. If the method is not declared public, its default modifier is also public. Any member variable defined in an interface is static and final by default.

Is the interface upcastable? In Java, there is no problem in upcasting a class to a parent class object, or upcasting it to an abstract parent class object, or upcasting a class to implement an interface.

A class can implement multiple interfaces at the same time. All interfaces that need to be inherited can be separated by commas after the implements keyword. In addition, interfaces can also be inherited.

The Singleton singleton pattern is used to create a globally shared instance object. The implementation principle is to privatize the constructor of the class, that is, use the private modifier to modify the constructor, so that the external cannot use the constructor to create objects, but objects can still be created inside this class, so you can create a The member variable of the class type is used to store the unique object of this class, and then the property accessor method is provided to obtain the unique instance, but the same object is obtained each time, rather than being recreated.

The values ​​of two basic data types can be directly judged by "==", but the two objects are two data structures stored in different memory spaces. To judge them, the "==" operator cannot be used, so only The memory addresses referenced by the two objects are compared, not the object contents. To determine whether the contents of two objects are the same, the equals() method must be used.

The final keyword is used in the Java language to decorate final types of classes and members. After being finalized, the content cannot usually be changed. In addition to modifying constants of basic data types, final can also modify object reference variables. Since array variables can also be regarded as an object reference, final can modify arrays. Once an object reference is modified as final, it can only point to one object invariably and cannot be changed to point to another object. A field that is both static and final occupies only a piece of storage that cannot be changed. Parameters of a method can be defined as final, which means that the parameter value cannot be changed in the method body or the object reference pointed to by the parameter cannot be changed.

A method defined as final cannot be overridden. Methods defined as final execute more efficiently than non-final methods. A method defined as private is implicitly designated as final type. A class defined as final cannot be inherited, all methods in a class are implicitly set as final, but member variables in a final class can be defined as final or non-final.

Classes redefined in other classes are called inner classes, and inner classes can be divided into member inner classes, local inner classes, and anonymous classes.

In the inner class of a class, you can directly access the private member variables of the class in which it is located. In the inner class, you can freely use the member methods and member variables of the outer class, regardless of whether these class members are modified as private.

The instance of the inner class must be bound to the instance of the outer class. If an inner class object is initialized from the outer class, the inner class object will be bound to the outer class object. Inner classes are initialized in the same way as other classes, using the new keyword. An instance's outer class creates an instance of the inner class in the same way that other classes create objects. An inner class can access the members of its outer class, but the members of the inner class are only known within the scope of the inner class and cannot be used by the outer class. If the inner class object is instantiated outside the outer class and non-static method, the type of the object needs to be specified in the form of outer class and inner class. To instantiate the inner class object of this instance in the main method or in another class, you must provide a reference to the outer class before the new operator.

When instantiating an object of an inner class, you cannot use the form of the name of the outer class before the new operator to instantiate the object of the inner class. Instead, you should use the object of the outer class to create an object of its inner class. An inner class object will depend on an outer class object, and an inner class object cannot be created unless an outer class object already exists. In addition, non-inner classes cannot be declared as private or protected access types.

If the member variable defined in the outer class has the same name as the member variable of the inner class, you can use the this keyword. A reference to an outer class can be obtained by using the outer class name followed by a dot operator and the this keyword.

Inner classes can be defined not only in the class, but also in the local location of the class. The inner class defined in the method can only access the local variable of the final type in the method, because the local variable defined in the method is equivalent to a constant, and its life cycle exceeds the life cycle of the method operation, because the local variable is set to final, so the value of this local variable cannot be changed in the inner class.

Add the static modifier before an inner class, and the inner class becomes a static inner class. A static inner class can declare static members, but cannot declare static members in a non-static inner class. The biggest feature of a static inner class is that non-static members of the outer class cannot be used. Two characteristics of static inner class: if you create an object of static inner class, you do not need a reference to the object of the outer class; you cannot access the object of non-static outer class from the object of the static inner class.

An exception is an event that occurs during program execution that interrupts the normally specified process of the executing program. Exceptions are also objects in the Java language. When an exception occurs in a method, the method creates an object and passes it to the runtime system. This object is the exception object.

The java language can catch the exceptions that may occur in the program, which is mainly done by the try...catch statement. The try statement block stores Java statements that may cause exceptions. The catch block is used after the try block to handle the caught exception. In addition, the finally statement block is the last execution part of the exception handling structure. No matter how the code in the try block exits, the finally block will be executed. finally is an optional part.

Java's exception handling is structured: when an exception occurs in the statement in the try code block, the program will be transferred to the catch code block for execution. After executing the program code in the catch code block, it will continue to execute other codes after the catch code block. , the code following the exception statement in the try block will not be executed.

The parameter type Exception in parentheses after the catch keyword is the exception type passed from the try code block to the catch code block. The statement "e.printStackTrace();" in the catch code block is used to output the stack trace information of the exception. The three commonly used methods of exception objects are as follows: getMessage() function: get exception information; toString() function: convert the exception object into a string, including exception type and error information; printStackTrace() function: indicate the type of exception, properties, stack levels, and where they appear in the program.

A complete exception handling statement generally includes a finally statement. It is best to have code that handles exceptions in the catch block. In three special cases, the finally block will not be executed: an exception occurs in the finally statement block; System.exit() is used in the previous code to exit the program; the thread where the program is located dies.

If an exception may occur in a method, but you do not want to handle the exception in the current method, you can use the throws keyword to throw the exception upwards and let the caller handle the exception. In addition, the throws keyword can throw exceptions in methods.

The throws keyword is at the end of the method declaration, exceptions may occur in the method body, and these exceptions are thrown up to the caller of the method for processing. Multiple exceptions are separated by commas. After using the throws keyword to throw an exception to the last method caller, if you don't want to handle the exception, you can continue to throw it up, but eventually you have code that can handle the exception. In the case of Error, RuntimeException, or their subclasses, the exception to be thrown can be declared without the throws keyword. Compilation still passes smoothly, but it is thrown by the system at runtime.

The throws keyword is usually used in method bodies, it is used for intentional exception throwing. When the program executes to the throws statement, it terminates immediately, and the statements after it are not executed unless the caller catches and handles the exception. throws is usually used to throw user-defined exceptions, and custom exceptions are implemented through the base Exception class. This class is the parent class of all catchable exceptions. In the try...catch statement, the order of multiple catches must follow the rule that the subclass is above the parent class.

RuntimeException is an exception generated during program running. All exception classes are subclasses of the Throwable class. The Throwable class derives two subclasses, the Exception and Error classes. The Error class and its subclasses are used to describe internal errors of the Java operating system and resource exhaustion errors, which are more serious. The Exception class is called a non-fatal class and can be handled by catching the program to continue execution. The Exception class is divided into RuntimeException exceptions and RuntimeException exceptions according to the cause of the error.

Types of RuntimeException
Types of RuntimeException illustrate
NullPointerException Null pointer exception class
ArrayIndexOutOfBoundsException Array subscript out of bounds exception
ArithmeticException Arithmetic exception class
ArrayStoreException Exception thrown when array contains incompatible values
IllegalArgumentException Illegal parameter exception
SecurityException Security exception
NegativeArraySizeException 数组长度为负异常

异常处理的主要作用是捕获程序在运行时发生的异常并进行相应的处理。

异常处理可遵循的原则:在当前方法声明中使用try-catch语句捕获异常;一个方法被重写时,重写它的方法必须抛出相同的异常或异常的子类;如果父类方法抛出多个异常,那么子类重写该方法必须抛出那些异常的一个子集。不能抛出新异常。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325646194&siteId=291194637