1. The concept of inheritance
1. The mechanism by which a parent class derives a subclass is called inheritance.
2. Inheritance is a powerful means of reusing program code. When the same properties and methods exist between multiple classes, the parent class can be abstracted from these classes.
3. We only need to define these properties and methods in the parent class, and the subclass does not need to redefine these properties and methods, and can directly inherit from the parent class.
4. Through inheritance, the subclass will automatically have the attributes and methods defined in the parent class.
5. If some of the members of two or more classes are the same, through the inheritance mechanism, existing classes can be used to create new classes.
6. Subclasses not only have members of the parent class, but can also define new members.
7. It can improve the reusability and scalability of software.
2. Parent class and subclass
1. Parent class: base class or super class
2. Child Class: Derived class or derived class
3. Implementation of inheritance
## Use the extends keyword.4. Access control
The Java language sets access control rules to restrict the use of class members from external classes##Access modifier
|
Self access
|
In-package access
|
Outside-package subclass access
|
Outside access
|
|||||||||||||
is |
Yes Yes Yes | protected |
是 | ||||||||||||||
是 是 |
No | Default |
Yes | ||||||||||||||
Yes No |
No | ##private | Yes |
||||||||||||||
No |
##No |
Note: Properties and methods modified with private in the parent class are transparent to the subclass and cannot be inherited. 5. Constructor methods in inheritance 1. The constructor method of the parent class cannot be inherited by the subclass 2. The subclass must call the parent -class structural method before performing its own structure. The call is divided into two types: A. Display call: The first sentence in the constructor of the subclass uses the key to use the super key in the constructor method of the subclass Word to specify which constructor of the parent class is called use use using using use use using using using use using ’ use use ’ through through using ’ out out through out through off out through through out through ’'s' itself'’’ ’ ‐ ‐‐ ‐‐ ‐‐‐‐ ‐ mark be d Construction method B. Ciscroof call: If the call is not displayed, the parent class has no parameter constructing method, which is equivalent to displaying the call super (), which means that when the default structure method of the parent class is called You can omit Super () Special attention: 1. The call order of the sub -class structure method is to call the parent class structure method first, and call the constructor of the subclass 2. When there is a default constructor in the parent class, the subclass constructor can omit the explicit call to the parent class constructor 3. When the parent class only has a constructor with parameters, the subclass The super keyword must be used in the constructor to display the constructor of the parent class 6. Class hierarchy 1.Java The language does not support multiple inheritance, that is, a class can only directly inherit one class. 2. A class can have multiple indirect parent classes. 3. All Java classes directly or indirectly inherit the java.lang.Object class 4. The Object class is the ancestor of all Java classes, and all Java classes are defined in the Object class Objects all have the same behavior 7. Default inheritance 1. When defining a class, the extends keyword is not used, then This class directly inherits from the Object class Chapter 8:JavaPolymorphism 1. The concept of polymorphism Official definition: Polymorphism means that calling member methods of a class will form different implementation methods Personal understanding: Parent class The reference points to the subclass object Effectively improve the scalability of the program. Based on writing
Dynamic polymorphism is also called dynamic binding. Usually when we say polymorphism, we generally refer to dynamic polymorphism. 2. Method rewriting If a method is defined in a subclass and its name, return value type and parameter list exactly match a method in the parent class, we can say that the subclass method overrides the parent class method. special attention: 1. Method rewriting must have inheritance relationships. The methods of the parent class are the same. #3. Polymorphic Application When a parent class reference points to a subclass object and a method is called through the reference, the subclass reuse is always called. The method after writingassigns the object of the subclass to the reference of the parent class. This behavior is called "upcasting", which can implicitly convertthe reference of the parent class back to the subclass. Quoting, this behavior is called "downward transformation", which needs to be compulsory conversion ## This special attention: When the cither of the parent class points to the sub -class object, the call of the method is dynamic analysis. That is, dynamic selection based on the actual type of the object is called dynamic binding 4. ObjectClass The Object class is the parent class or indirect parent class of all Java classes. According to the polymorphic characteristics, we can use the reference of the Object class to point to any object Note: If you can determine the specific type of the object referenced by Object, you can perform downward transformation (forced conversion) 5. equalsMethod The purpose of the equals method is to detect whether two objects are equal Provided by the Object class The implementation of the equals method is: detect whether the memory addresses of the two objects are in the same area (whether the memory addresses are equal) Usually we need to rewrite the equals method in order to redefine the rules for judgment Whether two objects are equal. Personal understanding: The equals method is to customize the game rules and formulate the conditions for object equality according to our needs Six,toString Method## The toString method returns a string describing the object (this must be rewritten when using the object directly for output) Method) Personal understanding: Simplify the process of outputting object information. After rewriting, you can directly output the objectSeven, final Keywords The final keyword can be used to modify classes, methods and variables. Final means immutable 1. When final modifies a class: it means that the class is not allowed to be inherited by other classes 2. When final modifies a method: it means that the method is not allowed to be overridden by subclasses 3. When When final modifies a variable: it means that the variable is a constant
Note: constants modified with final must be explicitly initialized Chapter 9: Abstract Classes and Interfaces 1. Abstract Class Concept Looking at the inheritance diagram of a class from bottom to top, we find that classes gradually become more general and more abstract. Due to the general nature of class variables, we will not be able to create meaningful implementation processes for methods in classes. Sometimes we need a parent class that only defines a general form that can be shared by all its subclasses, and lets each subclass supplement the implementation details. Such a class is called an abstract class . Note: A class containing an abstract method must be an abstract class. An abstract class can contain attributes and non-abstract methods. 2. Abstract method When defining a Java method, you can only define the declaration part of the method without writing the method body ( That is, the implementation details of the method), such a method is called an abstract method. Note: Abstract methods must be modified with the abstract keyword class. 3. Special attention èAbstract classes and abstract methods must be modified with the abstract keyword èAbstract methods There is no method body, and there is no pair of braces. There must be a semicolon after the parameter list èIf the class contains an abstract method, then the class must be an abstract class, but on the contrary, the abstract class does not Does not necessarily contain abstract methods. èAbstract classes cannot be instantiated (that is, objects of abstract classes cannot be created) èStatic methods can be declared in abstract classes 4. The use of abstract classes Since abstract classes cannot create objects, we can only use abstract classes through inheritance. (Supports polymorphism) Note: 1. If the subclass inherits an abstract class, then the subclass must override all abstract methods in the parent class 2. If an abstract class inherits another abstract class, then the subclass does not need to override the abstract method in the parent class 5. Summary of abstract classes abstract class is mainly inherited by the subclass, and then the subclass is played. Then the role of the abstract class is mainly manifested in the following two aspects: ## 1. Code reuse (surface phenomenon ) 2. Plan the behavior of its subclasses (key understanding) Use one sentence to summarize abstract classes: Abstract classes are abstractions of classes6. Interface concepts ## 不 Do not support more inheritance in Java, but provide strong interface support # interface: The methods in the class are specified, and there is no need to consider the inheritance relationship between classes A class can only directly inherit one parent class, but can implement multiple interfacesAn interface is a collection of abstract methods and static constants. In essence, an interface is a special abstract class. This abstract class can only contain the definition of abstract methods and static constants, but does not have variables and methods. Implementation 7. Pay special attention Because the methods defined in the interface must be abstract methods, you can define abstract methods in the interface as Omit the public and abstract keywords Because the variables defined in the interface must be static constants, you can omit the public, static, and final keywords when defining static constants in the interface 8. Use of interfaces ## Similar to inheritance, Java classes can implement interfaces, and implementation classes must override all abstract methods in the interface An implementation class can implement multiple interfaces, each interface is separated by a comma. An interface can also be implemented by multiple classes Interfaces also support polymorphic programming: interface references point to implementation class objects that that support multiple inheritance are supported. Summary of interfaces: Interfaces are abstractions of behaviors (i.e. methods)10. Comparison of interfaces and abstract classes 1. Similarities : dict t to Differences:been can have Impact, but for interfaces, they should not be changed once created. 11. Predefined interface Comparable There is an Arrays class in the java.util package. The sort method of this class can sort an Sort the object array, but there is a prerequisite that the objects in the array must implement the Comparable interfaceChapter 1: Exception Handling 1. Exception Concept Exception (Exception) refers to an event that occurs during program running, which can interrupt the normal execution of program instructions In Java language , exceptions can be divided into two categories: Error (Error): refers to internal errors in the JVM system, resource exhaustion and other serious situations Exception: due to programming errors or accidental General problems caused by external factors, such as square root of negative numbers, null pointer access, trying to read non-existent files, and network connection interruption issues Java language provides a complete set of abnormal processing mechanisms. The correct use of this mechanism will help improve the robustness of the program 注意: Exception and error have a common parent Throwable ##2. Processing Mechanism 3. Exception handling characteristics 4. ExceptionClass 5. Common exception types ## ##Exception classes Description ##Array index out of bounds exception ##NullPointerException Class not found exception Input and output exception ##FileNotFoundException
SQLException
6. The purpose of exception handling èReturn to a safe and known state è Ability to allow the user to execute other commands èSave all work if possible èExit if necessary to avoid further harm èExceptions can only be used Due to abnormal situations, exceptions cannot be used to control the normal flow of the program may be too large. 7. Use exception handling Java provides try-catch-finally statement to support exception handling try block : Code that may generate exceptions Catch block: Handling code when an exception occurs Finally block: Unconditional execution code (usually used to release resources) 8. Throw statement Exception Chapter 3: Collection Framework 1. Collection Overview List (List): List collection to distinguish the order of elements, and allow repetitive elements Java collections can only store reference data type data (i.e. objects). In fact, the collection stores references to objects, not the objects themselves. The elements in the collection are equivalent to reference type variables 4.Collection##Interface ##5.ListInterface List interface is a sub-interface of Collection interface List interface regulations Users can precisely control the insertion position of list elements, and have added functions such as accessing elements based on indexes. Corresponding methods have been added to the interface. void add(int index,Object element) Object get(int index) Object set(int index,Object element) int indexOf(Object o) Object remove(int index) 6. ArrayList## The java.util.ArrayList class implements the List interface for Expressing an array list with variable length 8. Generics## The generic (Gernerics) mechanism was introduced since JavaSE 5.0. It actually parameterizes the originally determined and unchanged types Benefits of generics: 1. As an expansion of the original java type system, the use of generics can improve the type safety, maintainability and reliability of java applications 2. Can solve the problem of data modeling in collections How to use: When creating a collection container, specify the element types it is allowed to save, and then the compiler is responsible for adding the type validity check of the elements. There is no need to perform styling processing when accessing the collection elements. Summary: Data type parameterization 9. HashSetClass TreeSetClass The java.util.TreeSet class also implements the java.util.Set interface, which describes the Set A variant of the collection that can implement sorting functions List##set and SetTraversal of collections List type collections: You can use ordinary for loops, super for loops and iterators to traverse Set type collections : You can use super for loops and iterators to traverse Note: Since the Set type collection has no index, you cannot use ordinary for loops to traverse Twelve, Map(Map) Map is a key A collection of objects for mapping, each element of which contains two objects (key objects and value objects) Typical Map type collections include HashMap and TreeMap Add element method: put( Object key, Object value) down ’ps together togetherps together out’s together's together's together's together's together's together's together's' together's'ps' right together out's' way's'ps' right together'ce’s rightOUT right clean right way cleanceumblececerce togetherce right together right clean right together right clean right together out right clean out, so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so so... Thirteen, TreeMap##Category Fourteen ,MapCollection traversal ## o #1. Overview Most programming work involves data transfer control (input/output) Java IO is implemented in a stream manner, that is, the transfer of data is regarded as the flow between the purpose and source of data Based on the difference in IO processing data, it is divided into: byte stream and character stream According to different functions: data flow and operation flow Treats bytes as the minimum transmission unit Composed of corresponding data streams and operation streams Character input stream abstract parent class: Reader Character output stream abstract parent class: Writer Reader/Writer FileReader/FileWriter Operation flow (high-level flow): BufferedReader/BufferedWriter ##5 , Byte character bridge stream 6.FileBasic concepts of classes Chapter 6: Thread 1. Threads and processes 2. Create threads ## 2. Rewill the Run method in the Thread class ## 3. Create a thread object 4. Call the start method to start the thread
# è Use the Runnable interface to create a thread to separate the CPU, code, and data. Form a clear model The implementation class can also inherit some useful properties and methods from other classes It is helpful to maintain the consistency of the program style è Directly inherit the Thread class creation Thread 2. Background Thread/Daemon Thread: Runs in the background, Usually some secondary threads that provide services to other threads, such as: garbage collection thread in JVM 3. User thread (User Thread): Thread created by the user or created by the system for the user ## 五 五 新 新 新 新 This provided by class: public final boolean isDaemon() // Determine whether a thread is a background thread When all user threads have stopped running, whether it exits normally or terminates early with an error, the JVM will exit. It can be understood that the background thread is not taken seriously and serves the user thread 6. Thread life cycle New state: Newly created thread object Ready state: Enters the ready state after calling the start method Running status: control from the thread scheduling of JVM to control blocking status: When the incident that causes threads occurs, adjust the JVM thread scheduler to the blocking state, such as in the thread Perform IO operations or wait for events such as data input from the keyboard Termination state: When all programs in the run method are executed, the thread will enter the termination state Special Note: It is forbidden to start a terminated thread again, and a thread is not allowed to be started multiple times 7. Thread priority The priority of a Java thread is represented by a number, ranging from 1 to 10 The default priority of the main thread is 5, and the priority of the child thread is the same as the priority of its parent thread by default Relevant methods provided by the Thread class Public final int getPriority()//Get the priority of the thread Public final void setPriority(int newPriority)//Set the priority of the thread Relevant static integer constants: Thread.MIN_PRIORITY=1 Thread.MAX_PRIORITY=10 Thread.NORM_PRIORITY=5 Execute the currently running thread to enter the blocking state, and then wake up and transfer to the ready state after the specified "delay time" Related methods provided by the Thread class: public static void sleep(long millis) Public static void sleep(long millis,int nanos) Note: 1 second = 1000 milliseconds, 1 millisecond = 1 million nanoseconds 9. Thread concession Let the running thread actively give up the CPU processing opportunity currently obtained, but instead of blocking the thread, it will redirect it Enter the ready state Relevant methods provided by the Thread class: public static void yield() 10. Thread suspension and recovery : Specify the threads in the current operation so that it can be transferred to the blocking state, and it will not automatically recover. Relevant methods provided by the Thread class: public final void suspend()//Thread suspension ##11. Thread synchronization and deadlock (2) Synchronization method ’ ’ s ’ s ’ ’ ’ ’ ’ minate There are some guidelines that can be followed that go a long way in avoiding the risk of deadlocks and performance hazards: Move preprocessing and postprocessing that do not change with threads out of synchronized blocks. (2) Do not block. Such as user input and other operations. (3) Do not call the synchronization method for other objects when holding a lock. 4. Thread deadlock: Too much synchronization may cause deadlock. Deadlock operations generally only occur when the program is running. can be shared in multiple threads, requires synchronization, but too much synchronization may cause deadlock. 1. What is a computer network? system, so that more computers can easily transfer information to each other and share resources such as hardware, software and data2. Socket Programming ## For "Socket" (Socket) Socket is usually used to implement Client-Server connection Two classes Socket and ServerSocket are defined in the java.net package, which are used to implement bidirectional Connected client and server3. 1. Establish a network connection 2. Open the input/output stream connected to the Socket 3. Read data through the opened IO stream/ Writing operation 4. Close the opened IO stream and Socket objectSupplementary content 1: Graphical user interface Swing AWT AWT: Early Java included an Abstract Window Toolkit (AWT) class library for basic GUI programming, such as Button, Checkbox, List, etc. These classes are all subclasses of the Component class AWT components are considered heavyweight components because they rely on the local system to support drawing and display. Each AWT component has a related component in the local window system Swing component It is written in pure Java code and is called a lightweight component. It does not rely on local components to support its display, but is completely drawn and displayed by Java code, so it is much more efficient than the usual AWT component. Swing: The Swing library is newer. In order to avoid duplication of names, all Swing component classes start with the capital letter J. Most of the Swing components are sub -categories of JCOMPONENENENENENENENENENENENENENENENENENENENENT class ## 二 2. Window container ## JFRAME (window): top application Program window JDialog (Dialog): Modal and modeless dialog boxes that collect user input JPanel (Panel): A small container that accommodates part of the interface JDBC 1. Overview Most development languages provide database Visit # JDBC is a set of interfaces and classes provided by Sun Company. It is encapsulated in the Java.SQL package and used to access the third -party driver and class provided by the database # database manufacturer package, you can access a specific database 2.JDBC## Connectivity) Java database connection, supports Java applications to connect to the database 1. Do a good job of preparing for a certain database Load the JDBC driver identification data Yuan 2. Establish a connection channel with the database allocated a Connection object 3. Start request to show what you want to do Allocate a Statement object Use the Statement object to execute sql statements ## 四, related categories and interfaces Driver management provides management functions for different database drivers java.sql.Driver interface The enumeration class defined by enum keywords is actually equivalent to defining a class. Such inherits the enum class. |
The above is the detailed content of Detailed introduction to java inheritance. For more information, please follow other related articles on the PHP Chinese website!