Hello, everyone! I'm Xiao Sheng! The teacher of the training class inspected the foundation a few days ago and found that there are still many loopholes. I want to further learn the foundation of Java, so I followed Mr. Han to learn Java. Here are my notes
Brief introduction to the distribution of IDEA development tools
package
The essence of the folder class is the file package keyword
Function: 1 Distinguish between classes with the same name 2 Can be a good management class 3 Control method scope through access modifier
Rules and specifications for packages
Package naming rules: it can only contain arrays, letters, underscores and small dots, but it can't start with arrays, keywords or reserved words
Package naming specification: the full name is lowercase letters + small dots
For example: com Company name. Project name Business module name
Common package
*It means that all classes under the package are imported
Attention to detail
-
The function of package is to declare the package of the current class, which needs to be placed on the top of the class (meaning that nothing can be placed on the package except comments). A class can only have one package at most
-
The import keyword is placed under the package. In front of the class definition, there can be multiple sentences without order requirements
// There is at most one package in a class package com.al_tair.study; // The import keyword is placed under the package. In front of the class definition, there can be multiple sentences without order requirements import java.util.Scanner; import java.util.Arrays; // Class definition public class study{ public static void main(String[]args){} }
Access modifier
Type of access modifier
- public: open to all classes in the package
- protected: expose subclasses of different packages and classes in the same package
- Default access modifier (no modifier): expose classes (including subclasses) in the same package, but not subclasses in different packages
- private: only the class itself can be accessed
Pay attention to details
- Modifiers can be used to modify properties, member methods, and classes in a class
- Classes can only be decorated with default and public
Three characteristics of object-oriented programming
Encapsulation, inheritance, polymorphism
encapsulation
Concept: it encapsulates the abstract data [attribute] and the data operation [method], the data is protected internally, and other parts of the program can operate the data only through the authorized operation [method]
Benefits: 1 Hide implementation details 2 The data can be verified to ensure the safety and rationality of the data
Implementation steps of encapsulation
inherit
extends keyword
Format: class subclass extends parent class {}
Benefits: to solve the problem of code reusability, when multiple classes have the same attributes and methods, we can extract the same attributes and methods as the parent class
Pay attention to details
-
The subclass inherits all the properties and methods of the parent class, but the private properties and methods cannot be accessed directly. The logical relationship between the subclass and the parent class must meet the is - a
-
The subclass must call the constructor of the parent class to complete the initialization of the parent class. The default is the parameterless parent class constructor. When the parent class has no parameterless constructor and the subclass does not use super to indicate the constructor of the corresponding parent class, the compilation will not pass
// Parent class public class person { public person() { System.out.println("Parent constructor"); } } // Subclass public class Child extends person{ public Child() { // Default super(); System.out.println("Subclass constructor"); } } class test{ public static void main(String[] args) { Child child = new Child(); } } // Running results Parent constructor Subclass constructor
-
The super and this keyword must be placed on the first line of the constructor when used, so the two method calls cannot share a constructor
-
All java classes are subclasses of the Object class
-
The call of the constructor of the parent class is not limited to the direct parent class, but will go back to the Object class (top-level parent class)
-
The mechanism can inherit at most one parent-child class
Memory distribution map
Find attribute and method data according to the principle of proximity
Explain super keyword
Usage: super represents the reference of the parent class and is used to access the methods, properties and constructors of the parent class
Attention to details:
- Cannot access private methods and properties of the parent class
- When using, it must be placed in the first line of the constructor, so the constructor of the parent class can only be called once
- In order to duplicate the name of the parent class and the child class of the superclass, the superclass must be accessed through the keyword
The difference between this and super
polymorphic
Concept: methods or objects have multiple states, and polymorphism is based on encapsulation and inheritance
The overloading and rewriting of methods reflect the polymorphism of methods
Concrete embodiment of object polymorphism
-
Prerequisite: there is an inheritance relationship between two objects (classes)
-
The compile type and run type of an object can be inconsistent
// Animal parent Dog subclass Cat subclass Animal animal = new Dog(); // Compile type Aniaml run type Dog animal = new Cat(); // The operation type can be changed
-
The compilation type is determined when the object is defined
-
The operation type can be changed
-
The compilation type depends on the definition, and the operation type depends on the new object
Detail analysis
-
Polymorphic upward transformation
- Essence: the reference of the parent class points to the object of the child class
- Syntax: parent type reference name = new subclass type ();
- Features: the compilation type depends on the definition, and the operation type depends on the new object
- When calling a method with this object, you can only call the method in the parent class, not the method specific to the child class, because the compilation fails; However, the calling method starts from the subclass to find the method in the running type
- Property is not rewritten, so the value of the property depends on the compilation type
-
Polymorphic downward transformation
-
Syntax: subclass type reference name = (subclass type) parent class reference;
-
Only references of the parent class can be coerced, and objects of the parent class cannot be coerced
-
You can call all members in a subclass type
-
My understanding is to unify the compilation and running types
// give an example Animal animal = new Dog(); // Compile type Aniaml run type Dog Dog dog = (Dog) animal; // //Compile type Dog run type Dog
-
Dynamic binding mechanism
Specifically:
- When calling an object method, the method will be dynamically bound with the memory address / running type of the object
- There is no dynamic binding when calling the properties of an object
For example:
// give an example public class demo{ public static void main(String[] args){ father f = new son(); System.out.println(f.sum()); // 40 System.out.println(f.sum2()); // 60 } } class father{ // Parent class public int attribute = 10; public int sum(){ return getAttribute() + 10; // getAttribute() binds the method of the subclass } public int sum2(){ return attribute + 50; // Property has no dynamic binding mechanism } public int getAttribute(){ return attribute; } } class son extends father{ // Subclass public int attribute = 30; public int getAttribute(){ return attribute; } }
Detailed explanation of Object class
equals
Difference between equals method and = = comparison operator
==: if the basic data type is judged, judge whether the values are the same; If the reference data type is judged, it is judged whether the address is the same (whether it is the same object)
equals: a method in the Object class, which can only be used to judge the reference type. By default, it is used to judge whether the addresses are the same. However, like the String class, this method is rewritten to judge whether the String values are the same
// Source code of Object class public boolean equals(Object obj) { return (this == obj); } // Source code of String class /** * Compares this string to the specified object. The result is {@code * true} if and only if the argument is not {@code null} and is a {@code * String} object that represents the same sequence of characters as this * object. */ public boolean equals(Object anObject) { if (this == anObject) { // Compare whether the addresses are the same return true; } if (anObject instanceof String) { // Judge whether it is a String or a parent class of String String aString = (String)anObject; // Downward Transformation: the purpose is to obtain the properties and methods of the String class if (!COMPACT_STRINGS || this.coder == aString.coder) { return StringLatin1.equals(value, aString.value); } } return false; } // The bottom layer of the source code of the StringLatin1 class is to compare whether each character in the character array is the same @HotSpotIntrinsicCandidate public static boolean equals(byte[] value, byte[] other) { if (value.length == other.length) { for (int i = 0; i < value.length; i++) { if (value[i] != other[i]) { return false; } } return true; } return false; }
hashCode
Function: returns the hash code value of the object to improve the performance of the hash table
Pay attention to details
- Improve the efficiency of containers with hash structure
- If both references point to the same object, the hash value must be the same
- The hash value is mainly based on the address, and the internal address of the object is converted into an integer
toString
Default return: full class name + @ + hash value hexadecimal
Function: used to return the attribute information of the object
// Object source code // java.lang.Object@16b98e56 public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
Pay attention to details
-
When an object is output directly, the toString method is called by default
Object o = new Object(); System.out.println(o.toString()); // java.lang.Object@16b98e56 System.out.println(o); //java.lang.Object@16b98e56
finalize
Concept: this method is called by the object's garbage collector when the garbage collector determines that there are no more references to the object
Pay attention to details
-
When an object has no reference, the jvm virtual machine will destroy the object. Before destroying the object, the finalize method of the object will be called
public class person { public person() {} // This method has been abolished and is not recommended @Override protected void finalize() throws Throwable { System.out.println("I've been destroyed..."); } } class test{ public static void main(String[] args) { new person(); System.gc(); // Run the garbage collector } } // Display effect: I have been destroyed
-
The call of garbage collection mechanism is determined by the system. We can use system GC () actively triggers garbage collection mechanism
breakpoint debugging
Breakpoint debugging (idea) default shortcut
- F7: jump in method
- F8: execute code line by line
- shift+F8: jump out method
- F9: execute to the next breakpoint
How does Idea debug enter the Jdk source code
Solution 1
Use force step into: shortcut keys alt + shift + F7
Solution 2
This configuration is good:
Click setting -- > build, execution, deployment -- > debugger -- > stepping
Do not step into java. * in the classes, javax.* Uncheck
Relevant interview questions
1. Please explain the difference between final, finally and finalize
final is used to declare attributes, methods and classes, respectively indicating that attributes are immutable, methods cannot be overridden and classes cannot be inherited.
finally is part of the exception handling statement structure, indicating that it is always executed.
finalize is a method of the Object class. When the garbage collector executes, it will call this method of the recycled Object, which can override this method to provide other resources during garbage collection
Recycling, such as closing files, etc.
2. What are the characteristics of object-oriented
- Abstraction: abstraction is to ignore those aspects of a topic that are not related to the current goal, so as to pay more attention to those aspects related to the current goal. The abstract does not intend to understand all the problems, but only
Is to select a part of it, without some details for the time being. Abstraction includes two aspects: process abstraction and data abstraction. - Inheritance: inheritance is a hierarchical model of connecting classes, and allows and encourages the reuse of classes. It provides a way to clearly express commonalities. A new class of object can be derived from an existing class
This process is called class inheritance. The new class inherits the characteristics of the original class. The new class is called the derived class (subclass) of the original class, and the original class is called the base class (parent class) of the new class. derive
A class can inherit methods and instance variables from its base class, and a class can modify or add new methods to make them more suitable for special needs. - Encapsulation: encapsulation is to surround the process and data, and access to the data can only be through the defined interface. Object oriented computing begins with the basic concept that the real world can be described as a
A family of fully autonomous, encapsulated objects that access other objects through a protected interface. - Polymorphism: polymorphism refers to allowing different objects to respond to the same message. Polymorphism includes parametric polymorphism and inclusion polymorphism. Polymorphic languages are flexible, abstract and behavior sharing
The advantage of code sharing solves the problem of the same name of application functions.
3. Please explain whether Java supports multi inheritance
Classes in java do not support multiple inheritance, but only single inheritance (that is, a class has only one parent class). However, interfaces in Java support multiple inheritance, that is, a child interface can have multiple parent interfaces. (the function of the interface is to extend the function of the object. A sub interface inherits multiple parent interfaces, indicating that the sub interface extends multiple functions. When the class implements the interface, the class extends the corresponding functions)