Java learning notes (language foundation and object-oriented)

Tengmu 2022-02-13 08:40:30 阅读数:946

java learning notes language foundation

Java Language Overview

  • Java virtual machine (JVM : Java Virtual Machine)
    java Language is responsible for interpreting and executing bytecode files , Is to run Java A virtual computer with bytecode files .
    When using Java Compiler compilation Java The program , It generates platform-independent bytecode , These bytecodes are not platform specific , Only for JVM.
    On different platforms JVM It's all different , But they all provide the same interface .
  • Java Standardized development package (JDK : Java SE Development Kit)
    Provides compilation 、 function Java The various tools and resources required for a program ( Include Java compiler 、Java Runtime environment and common Java The class library etc. )
  • Java Runtime environment (JRE : Java Runtime Enviroment)
    JRE And JVM The relationship between :JRE contain JVM,JVM Is to run Java The core virtual machine of the program , And running Java Programs don't just need core virtual machines , You also need other class loaders 、 Bytecode verifier and basic class library .JRE Except include JVM outside , It also includes running Java Other environmental support for the program .
  • How does the computer find commands ?( Reasons for setting environment variables )
    Windows according to Path Environment variables to find commands ,Path The value of the environment variable is a series of paths , The system will look for commands in sequence according to this series of paths . If you can find this command , execute ; If you can't find this command , Will appear :'xxx’ Not an internal or external command , Nor are they runnable programs or batch files .
  • About CLASSPATH
    If you use 1.4 The previous version of JDK, Need to set up CLASSPATH The value of the environment variable is
    .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar
    Once the environment variable is set ,JRE The search will follow the path specified by the environment variable Java class .
    spot ( . ) Represents the current path , To force Java The interpreter searches under the current path Java class .
  • Java Naming rules for source files
    If Java The source code of the source program defines a public class , The main file name of the source file must be the same as public Class has the same class name .( therefore , One Java There can be at most one... In the source file public class )
    If there is... In a source file 3 Classes , Then use javac Command compilation generates 3 individual .class file , Each class corresponds to a .class file .
  • Suggestions for improving readability
  1. One Java Source files usually define only one class , Different classes use different source file definitions .
  2. Give Way Java The main file name of the source file is the same as that defined in the source file public Class name .
  • Garbage collection (Garbage Collection , GC)
    JRE Mechanism for reclaiming useless memory . Usually JRE A background thread is provided for detection and control , It's usually in CPU Automatic garbage collection when free or out of memory .
  • Java Heap memory for
    Is a runtime data area , To save an instance of a class . Heap memory stores all objects created by running applications , These objects do not need to be explicitly released by the program through code . The garbage collector is responsible for the collection of heap memory , be-all JVM Each implementation has a heap memory managed by the garbage collector .

Data types and operators

Automatic promotion rule

byte -> short&char -> int -> long -> float -> double

  1. be-all byte、short and char All types will be promoted to int type .
short value = 5;
value = value - 2;
// there value-2 Automatically promoted to int type ,int Assign to short There may be a mistake 
  1. The data type of the entire arithmetic expression is automatically promoted to the same type as the highest level operands in the expression
byte b = 40;
var c = 'a';
var i = 23;
var d = .314;
double ans = b + c + i * d;
System.out.print(ans);// Output 7

Direct measurement

It refers to the value given directly through the source code in the program .

int a = 1; //1 Direct quantity 
double b = 2.0; //2.0 Direct quantity 
String name = "MJT"; //"MJT" Direct quantity 

String The direct quantity of a class cannot be assigned to variables of other types .
null The direct quantity of type can be directly assigned to any variable of reference type , Include String type .
boolean The direct quantity of type can only be assigned to boolean Variable of type , Cannot be assigned to any other type of variable .

Constant pool

Refers to when the compiler is determined , And saved in the compiled .class Some data in the file .
Include about classes 、 Method 、 Constants in the interface , It also includes the direct quantity in the string .

// Below "hello" Are stored in the constant pool 
var s1 = "hello";
var s2 = "hello";
var s3 = "he" + "llo";

Java Ensure that each string constant has only one , No multiple copies will be generated .
therefore , The three above "hello" In the constant pool is the same piece of data .

An operation

Operator name function
& Bitwise AND Also for 1 When to return to 1
| Press bit or As long as there is one for 1 Then return to 1
~ Bitwise non Monocular operator , Used to reverse .
^ Bitwise XOR Return... When two bits are the same 0, Not at the same time 1
<< Shift left operator Right side mend 0. Left beyond truncation
>> Shift right operator It turns out to be a positive number , Then fill zero on the left ; It's plural , Then the left side is added. 1. The right side is beyond the truncation
>>> Unsigned shift right operator The left side is always filled with zero . The right side is beyond the truncation

n>>x amount to n multiply 2 Of x Power .
n<<x amount to n Divide 2 Of x Power .

An array type

  1. initiate static : Specify the initial value explicitly , The system determines the length of the array .
// The first way 
int[] arr;
arr = new int[] {
1,2,3};
// The second way ( recommend )
var arr = new int[] {
1,2,3};
  1. dynamic initialization : Specify length explicitly , The system allocates the initial value .
// The first way 
int[] arr = new int[10];
// The second way ( recommend )
var arr = new int[10];
  1. Dynamically initialize allocation rules
Array element type Automatically assigned value
Integer types 0
Floating point type 0.0
Character (char) ‘\u0000’
Boolean type false
Reference type ( class , Interface , Array ) null

foreach loop

Take traversing array elements as an example

var arrs = new int[] {
1,2,3};
for (int arr : arrs) {

System.out.println(arr);
}

Use foreach When iterating over array elements in a loop , You can't change the value of an array element , Therefore, it is not applied foreach Assign a value to the loop variable of .

Drill down into arrays

Java in “ Array elements ” and “ An array variable ( Reference variables )” It is stored separately in memory . Take a chestnut :

int[] p;// Define a local variable 

there p It's a reference variable , Stored as a local variable in Stack memory in .
amount to C++ The pointer in , Point to one int Element memory .

p = new int[] {
1,2,3};

Actual array elements {1,2,3} Stored in new A piece opened up Heap memory in ,p = new int[] {1,2,3}; Then let p The reference variable points to the heap memory .

Two dimensional array

// Dynamic initialization mode 
int[][] arr;
arr = new int[2][];
// Static initialization mode 
int[][] arr = new int[][] {
new int[2],new int[]{
1,2,3}};

This two-dimensional array can actually be regarded as a one-dimensional array : Use new int[4] After initializing the one-dimensional array , It's equivalent to defining 4 individual int Variable of type ;
Allied , Use new int[4][] After initializing the array , amount to Defined 4 individual int[] Variable of type , these int[] Variables of type are all array types , So you have to initialize these arrays again .

object-oriented ( On )

About static The problem of

Why static members ( Members of the class ) No direct access to non static members ( Object members )?

First understand the basic concepts in several books

Main tune : Calling a member variable 、 The object of the method is called the master . Such as : Main tune . Method ();

Basic concepts (1): If the static Ignoring the main tone when decorating members of , This class is used as the main tone by default .

// Calling static When using the method, the following two forms are the same .
static_fun();
ClassName.static_fun();

Basic concepts (2): If the call does not static Ignoring the main tone when decorating members of , So by default this As the keynote .

// When calling ordinary members, the following two forms are the same .
fun();
this.fun();

Basic concepts (3):this Point to an instance of this class , and static Members belong to classes , therefore static Cannot use... Within a member this.

If an ordinary member is called in a static member , What's going to happen ? Take a chestnut :

public class test
{

public void show()
{

System.out.println("HelloWorld");
}
public static void main(String[] args)
{

show();
}
}
=============== Running results =================
error : Cannot reference non static from a static context Method show()

This corresponds to the basic concept (2), What is called here is an ordinary member function show, It is used by default this As the keynote .
This is the same thing as this.show();
but show() Can only be accessed through objects , and static Methods belong to classes , stay static Internal this I don't know which instance to point to , therefore show() Cannot be in main Method is called .

If you really want to static Method invocation static Method , You can create an object temporarily :

public class test
{

public void show()
{

System.out.println("HelloWorld");
}
public static void main(String[] args)
{

// Create a temporary object to call the show Method .
new test().show();
}
}

Method's parameter passing mechanism

Java There is only one mechanism for passing parameters : Value passed

For parameter passing of reference type , The same is the value passing method . But here “ value ”, Is the address value . such as :

class Data{

int num1=1;
int num2=2;
}
public class Test
{

public static void swap(Data p)
{

var temp = p.num1;
p.num1 = p.num2;
p.num2 = temp;
}
public static void main(String[] args)
{

Data a; // Define a Data Type references 
a = new Data(); //a The reference points to a block with new A newly opened piece Data Memory space .
swap(a); // Value passed ,p Accept a Address value of , bring p And a Store the same address value .
System.out.println(a.num1 + " " + a.num2);
}
}

The method of variable number of parameters

Method : Add three points after the last parameter type (Typename… name)

public class Test
{

public static void fun(int num,String... books)
{

for (String string : books) {

System.out.println(string);
}
}
public static void main(String[] args)
{

// The parameters can be listed directly 
fun(3,"Java","C++","Python");
// You can also String... regard as String[], Pass an array into .
fun(3,new String[] {
"Java","C++","Python"});
}
}

Must be Typename… The formal parameter is placed in the last position , Otherwise, an error will be reported .

Member variables and local variables

Member variables : Variables defined within a class . No explicit initialization required , The system automatically initializes .
local variable : Variables defined in methods . Requires explicit initialization .

The initialization of member variables and the running mechanism in memory

When the system loads a class or creates an instance of that class , The system automatically allocates memory space for member variables .

Take a chestnut :
For example, we have a class

class Person{

public static int eyeNum;
public String name;
}

1) If this class is loaded for the first time in the main function :

new Person();

Will the initialization Person class , Initialize only static variables ( Class variables )↑

2) And then create a Person Object of type

var p1 = new Person();

Create a Person You don't need to be eyeName Class variables allocate memory
System only for name Instance variables allocate memory space

3) Create a second Person Class object

var p2 = new Person();
p2.name = " Zhang San ";

The system allocates memory space only for the object members of the second object

The initialization of local variables and the operation mechanism in memory

int a; // The system does not allocate space 
a = 1; // Space is allocated only when assignment 
  1. Local variables do not belong to any class or instance , So it's always kept in its In the stack memory of the method
  2. Because local variables only hold values of basic types or references to objects , therefore The memory area occupied by local variables is usually small

Access control character

private default protected public
In the same class
In the same bag
In subclass
On a global scale

Local variables cannot be decorated with access control characters

Tool method

Methods used only to assist other methods of this class . Should also use the private modification

package Packet mechanism

Several knowledge points

  1. The package mechanism is used to resolve the duplicate name conflict of classes , Management of class files .
  2. According to the code , The package name should be in lowercase letters .
  3. You should use the reverse of the domain name , Such as com.ccatom package .
  4. package Statement must be the first non comment statement in the source file .
  5. A source file can only specify one package
  6. Classes under the same package can directly access
  7. It is generally recommended that class File with the java Open source files .

Special note : The classes in the parent package use the classes in the child package , You must write the full package path of the class plus the class name .

such as com.ccatom There is a class under the package A,com.ccatom.child There is a class under the package B.
class A Use class B There must be com.ccatom.child.B, It's like this .

com.ccatom.child.B obj = new com.ccatom.child.B();

An example of using the package mechanism

// Defines the class of a sub package 
package com.ccatom.child;
public class B{

public static void show(){

System.out.println("Hello Package");
}
}
 The parent package class needs to use the child package class , Therefore, first compile the sub package source file :javac -d . B.java
Found in the following directory class file : Current directory \com\ccatom\child\B.class
// Then define a parent package class that uses a child package class 
package com.ccatom;
public class A{

public static void main(String[] args){

// Use the full name to use the subclass package 
com.ccatom.child.B obj = new com.ccatom.child.B();
obj.show();
}
}
 Compile parent package class source file :javac -d . A.java
Found in the following directory class file : Current directory \com\ccatom\A.class
 Run parent package :java com.ccatom.A
Output Hello Package

If compiling Java Not used for file -d Options , The compiler will not Java The source file generates the corresponding file structure .

import keyword

import Keywords are used to simplify the above source code , Simplify before :

package com.ccatom;
public class A{

public static void main(String[] args){

com.ccatom.child.B obj = new com.ccatom.child.B();
obj.show();
}
}

Use import Direct import class B, After simplification :

package com.ccatom;
import com.ccatom.child.B;//import Import sub package class B
public class A{

public static void main(String[] args){

B obj = new B(); // Simplify the operation here 
obj.show();
}

If you want to import all classes under a package , You can write like this :

import com.ccatom.*; // Imported com.ccatom All classes under the package 

JDK 1.5 You can do it later “ Static import ”, A static member variable or method used to import a specified class .
Such as , Import com.ccatom Class in the bag A Static method of fun() :

import static com.ccatom.A.fun;

You can also import classes A All static members in :

import static com.ccatom.A.*;

1.import The statement should appear in package After statement 、 Before class definition .
2.Java The default is to import all source files java.lang Package all classes , So you can use String and System class .
Use import You can omit the package name ; While using import static You can omit the class name .

Java Common bag

package contain for example
java.lang Core class ( No need to import ) String、Math、System、Thread
java.util Tool class / Interface and collection framework classes / Interface Arrays、List、Set
java.net Network programming related -
java.text Input / output class / Interface -
java.sql JDBC Database programming related classes / Interface -
java.awt Abstract window toolset , Used to build GUI -
java.swing Swing GUI Programming related classes -

Java Constructors

Be similar to C++ Constructors in

public class Test{

public String name;
public int age;
// A simple constructor , Used to initialize name and age
public Test(String name,int age){

this.name = name;
this.age = age;
}
public static void main(String[] args){

Test obj = new Test("MJT",20);
System.out.println(obj.name+" "+obj.age);
}
}

Can't say Java Objects are created entirely by the constructor : Before calling the constructor , The system has allocated memory space for the object , And perform default initialization for this object , This object has been generated . But this object cannot be accessed externally , Only through the... Of the internal constructor this To quote .

meanwhile , The above code customizes a constructor with parameters , Then you can't use new Test(); To create an instance , Because there is no parameterless constructor in the class . So you need to do Constructor Overload ( There are multiple constructors in the same class , The formal parameter list of each constructor is different )

// Overload a parameterless constructor in the above class 
// You can use it new Test(); To create an instance 
public Test(){
}
  • Calls between constructors of the same class

One way is to use... In the constructor new Keyword to call another constructor , But it will recreate an object , Occupancy resources .
therefore , For constructors with inclusion relationships , Will be use this Call another overloaded constructor

public Test(String name){

this.name = name;
}
public Test(String name,int age){

this(name);// use this Call the overloaded constructor 
this.age = age;
}

What needs to be noted here is :

  1. Use this Call another overloaded constructor Can only be used in constructors ;
  2. Must be used as a constructor actuator The first line of the statement ;

Class inheritance

such as B Class to public Way inheritance A class :

public B extends A{
......}

Some tips to pay attention to :

  1. Java Abandoning the multi inheritance feature ,Java A class can only have one immediate parent ;
  2. Explicitly specify the parent class for , Then the default parent class java.lang.Object,java. therefore ,java.lang.Object Class is the parent of all classes ;
  3. Constructors cannot be inherited ;
  4. From a subclass perspective , Subclass extension (extends) Father class ;
  5. From a parent perspective , The parent class derives (derive) Out of subclass ;

Overrides the method of the parent class

Method rewriting (override): The phenomenon that a subclass contains a method with the same name as the parent class . Also known as method coverage

class A{

public void fun(){

System.out.println("A_fun");
}
}
public class B extends A{

// Override parent class A The method in fun
public void fun(){

System.out.println("B_fun");
}
public static void main(String[] args){

B obj = new B();
obj.fun();// Output B_fun
}
}

Static and non static methods cannot override each other

If there is one in the parent class private Method , Defining a method with the same name in a subclass does not constitute an override , Such as :

class A{

// The methods in the parent class are defined as private
private void fun(){
...}
}
class B extends A{

// You can use it here static limit , Because it doesn't belong to rewriting .
// Defined by the fun Is a new method of subclass 
public static void fun(){
...}
}

super limit

If you need to call a method that is overridden in the parent class in the subclass , It can be used super Qualifies to call the overridden method as the master . such as

class A{

public int a = 1;
}
public class B extends A{

public int a = 2;
public void show_a_in_A(){

// Use... In subclass methods super To call the instance variable of the parent class a
System.out.println(super.a);
}
public static void main(String[] args){

// Although the parent class a Quilt subclass a Cover 
// however new B(); It will still be in the parent class a Open up a piece of memory 
B obj = new B();
obj.show_a_in_A();// Output 1
}
}

Tips to pay attention to :

  1. Can be super And this Similar view ,super Cannot appear in static In the way of embellishment ;
  2. It doesn't completely cover , When the system creates a subclass object , Will still be defined in the parent class 、 Hidden variables allocate memory space ;

heavy load (overload) And rewriting (override)

heavy load : Occurs before multiple methods with the same name in the same class .
rewrite : Occurs between methods with the same name in a child class and a parent class .

There are exceptions. : If the subclass defines a method with the same name as the parent method , But the parameter list is different , The overloading of parent class methods and subclass methods will be formed .

The subclass calls the constructor of the parent class

Same class , Invoke another constructor in a constructor this Call to complete .
Allied , In the subclass constructor, call the constructor of the parent class. super Call to complete .

class A{

private String name;
public A(String n){

name = n;
}
}
public class B extends A{

private int age;
public B(String n,int a){

// Use super Qualify to call the constructor of the parent class 
super(n)
age = a;
}
public static void main(String[] args){

B obj = new B("MJT",20);
}
}

Tips to pay attention to :

  1. super When calling a parent constructor, it must also appear in the constructor's execution body first line ( therefore this Invocation and super Calls do not occur at the same time )
  2. When a subclass constructor is called to initialize a subclass object , The parent constructor always executes before the child constructor .
  3. super Call cannot be used in static In the way ( Constructor does not belong to class , It's impossible to use static modification )

polymorphic

  • polymorphic : Variables of the same type , When calling the same method, there are many different behavior characteristics .
  • Compile time type : Determined by the type of declared variable , Such as String s , that String Is the compile time type .
  • Runtime type : Determined by the object actually assigned to the variable , Such as var s = new String(); , that String Is the runtime type .
  • Upward transformation (upcasting): Assign a subclass object directly to a parent class reference variable

If the compile time type and run time type are not the same , There may be polymorphism
A similar form : Compile time type Variable name = new Runtime type ();

This type of polymorphism is divided into two cases :

The first is the case of rewriting members :
Come to the conclusion first :

Explain the chart : Variable name . Rewriting methods (); Called is a method that executes a runtime type , Which is equivalent to
Variable name . Execute methods of runtime type ();

Take code for example :

class Father{

// there num And show Corresponds to... In the chart “ Override instance variables ” And “ Rewriting methods ”
public int num = 1;
public void show(){

System.out.println("Father_show_override");
}
}
public class Child extends Father{

// Override... In subclass num Instance variables 
public int num = 3;
// Override... In subclass show Method 
public void show(){

System.out.println("Child_show_override");
}
public static void main(final String[] args){

final Father obj = new Child();
obj.show();// Call overridden show Method 
System.out.println(obj.num);// Output rewritten num Instance variables 
}
}

Then there is the case of unique members ( Subclasses have , The parents don't have or The parent class has no children )
Conclusion :

Code, for example :

class Father{

// Unique instance variables in the parent class 
public int father_num = 2;
// Methods unique to the parent class 
public void father_fun(){

System.out.println("Father_fun");
}
}
public class Child extends Father{

// Specific instance variables in subclasses 
public int child_num = 4;
// Methods specific to subclasses 
public void child_fun(){

System.out.println("Child_fun");
}
public static void main(final String[] args){

final Father obj = new Child();
obj.father_fun();// Call methods unique to the parent class 
System.out.println(obj.father_num);// Output instance variables unique to the parent class 
obj.child_fun();// Call methods specific to subclasses , Report errors 
System.out.println(obj.child_num);// Output specific instance variables in subclasses , Report errors 
}
}

instanceof Operator

  • Use : Binocular operator . The previous operand is usually a reference type variable , The latter operand is usually a class ( Or interface ).

  • effect : The following object or subclass is used to judge whether it is the preceding object or subclass ( Is to return true, If not, return to false).

  • application : Generally used for cast ( Up or down ) Scenario .

    for example : If you try to cast a parent instance to a subclass type , Then this object must be a subclass instance ( That is, the compile time type is the parent type , The runtime type is a subclass type ) Otherwise, it will be raised at run time ClassCastException abnormal .

    Usually instanceof and (type) Operator with : Usually first instanceof Determine whether an object can cast , And then use (type) Operator to cast , In order to ensure that the program will not be wrong .

    Take a chestnut :

    // If obj yes String Class or its subclasses 
    if(obj instanceof String){
    
    // Then we can put obj The object type is cast to the same or its parent type 
    var str = (String)obj;
    }
    

Considerations for using inheritance

  • Try to hide the internal data of the parent class , use private Modifier .
  • Don't let subclasses have free access to 、 Modify the method of the parent class . Tools and methods should use private modification ; Need to be called by an external class , Just use public modification , But I don't want subclasses to override this method , Just add one more final Modifier ; If you want a method to be overridden by subclasses , I don't want to be accessed by other classes , Just use protected Modifier .
  • Try not to call a child class rewrite in the parent constructor. .

Combine

  • For inheritance : Subclasses can directly get the parent class's public Method .
  • And for combinations : Combine the old class objects as member variables of the new class , To implement the functions of the new class .

Take a chestnut :

class A{

public void fun_A(){

System.out.println("Hello_World");
}
}
class B{

// Old class A The object of a As a new class B Member variables of .
// Here we use private, Because all we want users to see is the methods of the old class , Instead of old class objects .
private A a = new A();// Combine 
public void fun_A_in_B(){

// Thus, the method of the old class can be called within the method of the new class .
a.fun_A();
}
}
public class Test{

public static void main(String[] args){

var obj = new B();
obj.fun_A_in_B();
}
}

Combined memory costs : There is no essential difference in the system overhead between inheritance and composition design . Inherit as parent ( Old class ) Open up space , Also subclass ( A new class ) Open up space . The combination is the same , There is only one more reference variable than inheritance to refer to the embedded object , Generally, it has little impact .

Initialization block

  • Format :
[ Modifier ] {
// Executable code of initialization block
......
}
  • there [ Modifier ] If it is static, This code block is called Class initialization block
  • No, static modification , It is called a Instance initialization block

Instance initialization block

  • Instance initialization block is created only when Java Object is executed implicitly , And automatically before the constructor executes
public class Test{

{

System.out.println(" The first running instance initializes the block ");
}
{

System.out.println(" Initialization blocks are executed sequentially ");
}
public Test(){

System.out.println(" First run the initialization block and then run Test Constructors ");
}
public static void main(String[] args){

new Test();// Implicit execution when creating objects 
}
}
============= Execution results =============
The first running initialization block
Initialization blocks are executed sequentially
First run the initialization block and then run Test Constructors

Instance initialization block “ illusion ”: In fact, the instance initialization block will disappear after compilation , Is restored to the front of all code for each constructor

Class initialization block

  • The class initialization block is executed during the class initialization phase , Instead of executing... When creating objects . therefore Class initialization blocks are always executed before instance initialization blocks .
  • Class initialization block can only access static members .

【 a key 】 Instance initialization is fast 、 Class initialization fast 、 The execution order of the constructor


class Father{

static{

System.out.println(" Parent class initialization block ");
}
{

System.out.println(" Parent class instance initialization block ");
}
public Father(){

System.out.println(" The constructor of the parent class ");
}
}
class Child extends Father{

static{

System.out.println(" Subclass initialization block ");
}
{

System.out.println(" Initialize subclass instances ");
}
public Child(){

System.out.println(" Constructor of subclass ");
}
}
public class Test{

public static void main(String[] args){

// for the first time new Child();
new Child();
// The second time new Child();
new Child();
}
}

Use a flowchart to briefly describe the operation process ( Poor, I can only use the trial version of billion diagram ):

object-oriented ( Next )

Packaging

Java The basic type function in is simple , Does not have the characteristics of the object , In order to make the basic type have the characteristics of the object , So there are packaging classes , You can manipulate basic type data like an object .

// Define a wrapper class Integer The object of 
Integer int_obj = new Integer(1024);
  • Automatic boxing : Assign a basic type variable directly to the corresponding packaging class variable , Or give to Object Variable .
// Automatic boxing 
int num = 1024;// A basic type variable 
Integer int_obj=num;// Direct to Integer Packaging variables 
  • Automatic dismantling : Opposite to packing , Directly assign the wrapper class object to a corresponding basic type variable .
// Automatic dismantling 
Integer int_obj = new Integer(1024);// A wrapper class object 
int num = int_obj;// Directly assigned to basic type variables 
  • Correspondence between basic data types and wrapper classes
Basic data type Packaging
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean
  • Common methods of packaging

Print objects and toString Method

stay Java You can directly output class objects .
Take a chestnut :
First define a simple class , For output :

class Person{

private int num;
public Person(int num){

this.num = num;
}
}

stay main Function directly outputs Person Class object :

public class Test{

public static void main(String[] args){

Person obj = new Person(1024);
System.out.println(obj);// Directly output class objects 
}
}
============ Output results =============
Person@1f32e575

In fact, there is an implicit use of Object An instance method in the class toString()
And all Java Classes are Object Subclasses of classes , So all Java Objects all have toString() Method
The following two forms are equivalent :

System.out.println(obj);
System.out.println(obj.toString());

Object Class provides the toString() Method always returns the object's implementation class " Class name [email protected]+hashCode" value .
If you want to output the results we want , I can rewrite it toString Method .

class Person{

private int num;
public Person(int num){

this.num = num;
}
// Rewrite this toString Method (Object An instance method of class )
public String toString(){

return "[" + "num=" + num + "]";// Return the result we want 
}
}

compile javac -d . Test.java
function java Test
go ~~~~

[num=12]

It's still fun QAQ

== and equals Method

stay Java There are two ways to compare variables in : One is to make use of ==, The other is to make use of equals() Method .

First to speak == Operator .
This can directly compare basic data types ,C++ It's also often used in .
But if it's used to compare reference type variables , Only when two reference type variables point to the same object ,== Judgment will return true. Take a chestnut :

var num1 = Integer.valueOf(1024);
var num2 = Integer.valueOf(1024);
System.out.println(num1 == num2);
============ Output results =============
false

there num1 and num2 Are two reference type variables , Different addresses are stored , Pointing to different places ,== The direct judgment is the address , So output false

Let's talk about it again equals Method
equals() The method is Object Class provides an instance method , Therefore, all reference variables can call this method to determine whether it is equal to other reference variables .

var num1 = Integer.valueOf(1024);
var num2 = Integer.valueOf(1024);
System.out.println(num1.equals(num2));
============ Output results ==============
true

there equals() Method does not judge the address , It's the value it points to .

Customize equals() Method
This equals() Since it is Object class , and Object Class is the parent of all classes .
Then we can also customize toString() Method to customize equals() Slightly ~
Take a chestnut :
Let's define a " people " class , There are names and ages , As long as they are the same age , Let's judge these two as true
namely p1.equals(p2); Should return to true.

class Person{

private int age;// Age 
private String name;// full name 
public Person(int age,String name){

this.age = age;
this.name = name;
}
// rewrite equals Method , Just judge your age .
// Rewriting requires that the return value and formal parameters cannot be changed .
public boolean equals(Object obj){

return (this.age==obj.age?true:false);
}
}
public class Test{

public static void main(String[] args){

// Two people have different names , But the same age .
Person p1 = new Person(18, "Amy");
Person p2 = new Person(18, "Tom");
System.out.println(p1.equals(p2));
}
}

compile function go ~~~~~~

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
age cannot be resolved or is not a field
at Person.equals(Test.java:32)
at Test.main(Test.java:40)

emmm, It's a mistake .
The error message points to this paragraph

obj.age

obj As parent , did not age This variable .age yes Person A unique member of a subclass !
But I want to rewrite , The return value and formal parameters must not be changed , And there must be Object obj(equals The document says )
Then what shall I do? ??
Cast
That is, we need to make a downward transformation ,((Person)obj).age.
Also judge obj Is it right? Person Class object .

public boolean equals(Object obj){

// Judge obj Is the object Person Class object 
if(obj.getClass() == Person.class){

return (this.age==((Person)obj).age?true:false);
}
return false;
}

The other is constant compile function go ~~

true

Little details : Why ((Person)obj).age instead of (Person)obj.age ?
This is because the member operator (.) The priority of is higher than the parentheses .
(Person)obj.age Is equivalent to (Person)(obj.age)

final Member variables

  • Pre knowledge : Class initialization , The system allocates memory for class variables of this class , And assign the default value ; When you create an object , The system allocates memory for instance variables of the object , And assign the default value .
  • About final: use final Modified member variables , Once you have the initial value , Can't be reassigned .
  • Java Grammatical rules :final Decorated member variables must be explicitly specified by the programmer with initial values .
Variable type Can specify the position of the initial value
Class variables Static initialization block 、 When making a statement
Instance variables Non static initialization block 、 When making a statement 、 The constructor
/********** Class variables *********/
// Initialize when declaring 
final static int num = 1024;
// Initialization in static initialization block 
final static int num;
static{

num = 1024;
}
/********** Instance variables *********/
// Initialize when declaring 
final int num = 1024;
// Initialization in non static initialization block 
final int num;
{

num = 1024;
}
// Initialization in constructor 
final private int num;
public Test(int num){

this.num = num;
}

Particular attention : If it's going to be in the constructor 、 Initialization block for final Initialization of member variables , Do not access... Before initialization final Member variables .

final int num;
{

// It's not initialized yet num, This will give you an error 
System.out.println(num);
// however ,Java Allow access through methods final Variable .
// therefore , Through this fun() Method to indirectly access num
// Will cause the system to automatically num Fu 0
fun();
//fun() After that, the initial value has been assigned by the system 
// there num=1024 invalid 
num = 1024;
}
public void fun(){

System.out.println(num);
}

About final

final local variable

final The assignment of local variables can be changed slightly , First of all , Initialize later . such as :

public static void main(String[] args){

final int num;// First of all 
num = 1024;// Initialize later 
System.out.println(num);
}

final Reference type variable

For reference type variables , It just keeps a reference ,final Only ensure that the address pointed to by this reference type variable will not change .

“ Macro replace ” Of final Variable

For one final In terms of variables , As long as three conditions are met :

  1. Use final Modifier modifier .
  2. The initial value is specified at the same time as the definition .
  3. This initial value can be determined at compile time .

This final A variable is no longer a variable , It's equivalent to a direct quantity , Stored in the constant pool .

// The next two are final“ Macro variable ”
final var a = 5+2;
final var str1 = " Tengmu "+" Of ";
final var str2 = " Little world "
// The following initial values cannot be determined at compile time 
// Not treated as macro variables 
final var num = Integer.valueOf(1024);

final Method

final The decorated method cannot be overridden

One “ exception ”:

public class A{

// This is used here. private limit 
// about B Class is invisible 
final private fun(){
}
}
class B extends A{

// Therefore, this is equivalent to defining a new method 
// Belong to B Subclass 
public fun(){
}
}

final class

final The modified class cannot have subclasses

Immutable classes

immutable (immutable) Class means to create an instance of this class , The instance variables of this instance are immutable .

public class Test{

// Immutable classes need to use private and final Modifier member variable 
private final String str;
// You need to provide a constructor with parameters 
public Test(String str){

this.str = str;
}
// Only class members of this class are provided with getter Method 
// Does not provide setter Method 
}

An instance of an immutable class is always initialized throughout its life cycle .
Java Of 8 Packaging and java.lang.String Classes are immutable

abstract class

  1. Abstract classes can only be inherited , Can't use new instantiate .
  2. abstract You can't modify variables .
  3. Classes with abstract methods can only be abstract classes , Abstract classes can have no abstract methods .
  4. abstract And private No coexistence , Because in subclasses private Method not visible , You can't rewrite .
  5. final And abstract Can't coexist , Otherwise, the class cannot be inherited , Method cannot be overridden .
//Abs There's an abstract method inside ,Abs Can only be abstract classes 
public abstract Abs{

//abstract You can't modify variables 
private String name;
// The constructor of an abstract class cannot be used to create an instance 
// Mainly used to be called by other subclasses 
public Abs(){
}
public Abs(String name){

this.name = name;
}
// Abstract methods do not provide concrete implementations , Give it to the subclass implementation 
public abstract String getName();
}
  • Template pattern : If you write an abstract parent class , The parent class provides common methods for multiple subclasses , And leave one or more methods to subclass implementation . This design pattern is called template pattern .

An abstract class is a parent class abstracted from multiple concrete classes
Avoid the randomness of subclass design

Interface

If an abstract class is a template abstracted from multiple classes , Then the interface abstraction is more thorough .
Interfaces are abstracted from multiple similar classes standard , The interface does not provide any implementation .
The interface defines the specifications that a batch of classes need to comply with , The interface doesn't care about the internal state data of these classes , I don't care about the implementation details of the methods in these classes , It only states that certain methods must be provided in these classes , The classes that provide these methods can meet the actual needs .

Format :

[ Modifier ] interface The interface name extends The parent interface 1, The parent interface 2...
{
Various methods and constants
}

Some knowledge points :

  1. Modifier can only be public, Or not . Because interfaces are of multiple classes “ public ” standard .
  2. An interface cannot have an initialization block 、 Constructors .
  3. Interface member variables can only be static constants (int a = 1; The system automatically adds public static final modification ).
  4. Member variables of an interface can only be defined with default values .
  5. Interface methods can only be class methods 、 Abstract method ( The common method automatically adds abstract)、 Default method or private method .
  6. Common methods in interfaces ( Abstract method ) There can be no realization ; But class methods 、 The default method 、 Private methods must have methods to implement .
public interface Itf{

/********** Member variables **********/
int num = 1024;
// The system automatically adds public static final modification 
// You must specify a default value when defining 
/********** Abstract method **********/
void fun();
// The system automatically adds abstract
/********** The default method **********/
default void def_fun(){

System.out.println(" The default method ");
}
// Use default modification , Must be realized 
// The system automatically adds public Modifier 
/********** Class method **********/
static void sta_fun(){

System.out.println(" Class method ");
}
// The system automatically adds public Modifier 
/********** Private method **********/
private void pri_fun(){

System.out.println(" Private method ");
}
// have access to static Modifier modifier 
// Use as a tool method 
}

There can only be one... In a source file public Interface , The main file name must be the same as the interface name .

Use interface

Use format :

[ Modifier ] class Class name extends Parent class implements Interface 1, Interface 2...
{
......
}

The main purpose of the interface :

  1. Variables defining interface types , It can also be used to cast
  2. Calling constants defined in the interface
  3. The methods in the interface are implemented by other classes

Take a chestnut , Use the above Itf Interface :

public class Test implements Itf{

// Abstract methods for implementing interfaces , Need to use public
// Otherwise, an error will be reported : Attempting to assign lower access ; Used to be public
public void abs_fun(){

System.out.println(" Implements the abstract methods in the interface fun");
}
public static void main(String[] args){

Itf obj = new Test();
System.out.println(obj.num);// Call constants in the interface 
obj.abs_fun();// The object using the interface calls the abstract method implemented by the implementation class 
obj.def_fun();// You can call the default method of the interface directly 
Itf.sta_fun();// Use the interface to call the class method of the interface 
}
}
========== Output results ==========
1024
Implements the abstract methods in the interface fun
The default method
Class method

When implementing interface methods , You have to use public Modifier , Because the methods in the interface are public Of , When the subclass overrides the parent method, the access permission can only be greater or equal .

Exceptions and try / catch

  • Basic statement
public static void main(String[] args) {

try {

process1();
process2();
process3();
} catch (UnsupportedEncodingException e) {

System.out.println("Bad encoding");
} catch (IOException | NumberFormatException e) {

System.out.println("IO error");
} finally {

System.out.println("END");
}
}

Because processing IOException and NumberFormatException The code for is the same , So we use | Merge them together .
stay try-catch The scope of the variable declared within the statement is within the statement block , Not visible from the outside .
finally Statement is not necessary , Write but not write ;
finally Always last .

  • Java Inheritance diagram of exception class

  • A chestnut

Deliberately write an exception statement here 1/0.

public class Test {

public static void main(String[] args) {

String a = "12";
String b = "x9";
// TODO: Catch exceptions and handle 
int c = stringToInt(a);
int d = stringToInt(b);
System.out.println(c * d);
}
static int stringToInt(String s) {

return Integer.parseInt(s);
}
}

Compilation of normal , Throw an exception at runtime :

Exception in thread "main" java.lang.NumberFormatException: For input string: "x9"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:658)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at Test.stringToInt(Test.java:35)
at Test.main(Test.java:30)

It can be seen that it is NumberFormatException abnormal , It can be used at this time try-catch Catch the exception .

public class Test {

public static void main(String[] args) {

String a = "12";
String b = "x9";
int c = stringToInt(a);
int d;// Variable declaration should be in try-catch Out of statement 
try {

d = stringToInt(b);
} catch (NumberFormatException e) {

b = "19";
d = stringToInt(b);
}
System.out.println(c * d);
}
static int stringToInt(String s) {

return Integer.parseInt(s);
}
}
}

Will execute first try sentence , Throw out NumberFormatException After abnormality , The system will selectively execute catch sentence . It's a bit like switch sentence .

Use try … catch … finally when :

  1. Multiple catch The matching order of statements is very important , Subclasses must be placed first ;

  2. finally Statement ensures that it will be executed with or without exceptions , It's optional ;

  3. One catch Statement can also match multiple exceptions that are not inherited

copyright:author[Tengmu],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130839140784.html