Fundamentals of java syntax 1

1, Theory

1. Loading and execution of Java program

The running of Java program includes two important stages: compiling and running

Compilation phase

The main task is to check whether the Java source program complies with Java syntax, and if so, it can generate normal bytecode files. Bytecode files are not pure binary files, which cannot be executed directly in the operating system.

Process:

  1. The programmer needs to create a new one somewhere on the hard disk The file with Java extension is called Java file, and the Java source code is written in the source file.
  2. Java programmers need the Java. Net that comes with the JDK Exe command to compile Java programs. javac is a java compiler tool.
    Using javac in DOS window
  3. A java source file can be compiled to generate multiple Class file, so after the class file is deleted, the deletion of Java source file will not affect the execution of the program.
  4. After compilation, you can copy the class file to other operating systems for execution

Operation phase

  1. After JDK is installed, in addition to a Java Exe, there is another tool / command called Java Exe, which is mainly responsible for the running phase and is used in the DOS window.
    java class name
  2. Process:
    • Open DOS command window
    • Input: java A
    • java. The EXE command will start the Java virtual machine (JVM), and the JVM will start the ClassLoader
    • ClassLoader will search the hard disk for the A.class file. If it finds the file, it will load the bytecode file into the JVM.
    • The JVM interprets the A.class bytecode file as binary data
    • Finally, the operating system executes binary and interacts with the underlying hardware platform

2. JDK/JVM/JRE

JDK: java Development Kit

JRE: realtime environment

JVM: java virtual machine

3. Groceries

How the Windows operating system searches for a command on the hard disk:

  1. First, it will search under the current directory
  2. A command is searched from the path specified by the environment variable path
  3. If none of them can be searched, an error will be reported

----Solution: add environment variable: path=xxx;D:\Project_Java\jdk8u312-b07\bin

DOS running java program: (take "HelloWorld.java file as an example")

  1. You need to use Java Exe command

  2. First, test whether the java command is available

  3. Through javac Generate helloworld.exe Class file

  4. Usage: java class name
    There is HelloWorld on the hard disk Class, then the class name is HelloWorld
    java HelloWorld
    It must be noted that the java command is not followed by the file path, but the name of a class

  5. First, you need to switch the directory in the DOS window to HelloWorld The directory where the class file is located

  6. Then directly execute: java HelloWorld

  7. HelloWorld. The java file source code is as follows:

    public class HelloWorld  //Means to define an open class named HelloWorld
    {
    	//It is not allowed to write java statements directly in the class body, except for declaring variables
    	/*
    		public Indicates public
    		static Indicates static
    		void Indicates null
    		main Indicates that the method name is main
    		(String[] args) Is a formal parameter list of the main method
    
    		The method under is the main method of a program and the execution entry of the program
    	*/
    	public static void main(String[] args){  //Represents the definition of an exposed static main method
    
    		//Method body
    		//Method body
    		//Method body
    		
    		//java statement [java statement is marked with ";" [Termination]
    	
    		System.out.println("Hello World");  //Output a message to the console: Hello World
    		//All strings in java use double quotation marks
    	}
    }
    

Comments on java language:

  1. It appears in the java source program and explains the java source code

  2. Comments are not compiled into class bytecode

  3. A good development habit should be to write more comments, which can enhance the readability of the program!!!

  4. Writing method:

    //Single-Line Comments 
    
    /*
    	multiline comment 
    	multiline comment 
    	multiline comment 
    */
    
    /**
    *   javadoc notes
    *   javadoc notes
    *   javadoc notes
    */
    

The difference between public class and class

  1. Multiple calss can be defined in a java source file
  2. A java source file does not necessarily have a public class
  3. A class definition will generate a XXX Class bytecode file
  4. If a public class is defined in a java source file, there can only be one public class, and the name of the class must be consistent with the name of the Java source file

classpath

  1. By default, ClassLoader loads xxx from the current path Class bytecode file
  2. Of course, you can also let ClassLoader load bytecode files in a specified path. In this case, you need to configure the environment variable classpath
  3. The classpath environment variable belongs to the environment variable in the java language and does not belong to the windows operating system [PATH environment variable belongs to the operating system]
  4. classpath is used to guide the ClassLoader class loader.
  5. Set the environment variable: classpath = D: \ course \ javaprojects \ 02 javase \ 1
    – open the dos command window and execute it anywhere: java HelloWorld
  6. If the classpath environment variable is not configured, the classloader will find the bytecode file from the current path by default,
    When the classpath environment variable is configured to a specified path, the classloader will only load bytecode files in the specified path.

2, Fundamentals of programming language

1. Identifier

– what is an identifier?

  • In java source program, all the words that programmers have the right to command are identifiers.
  • The identifier is highlighted in black in the EditPlus editor.
  • The identifier can identify class name, method name, variable name, interface name and constant name.

– naming rules for identifiers?

  • It can only be composed of numbers, letters, underscores and dollar symbols.
  • Cannot start with a number
  • Strictly case sensitive
  • Keywords cannot be used as identifiers
  • Theoretically, there is no length limit

– naming conventions for identifiers?

  • Class name and interface name: the first letter is capitalized, and the first letter of each subsequent word is capitalized
  • Variable name and method name: the first letter is lowercase, and the first letter of each subsequent word is uppercase
  • Constant name: all uppercase

2. Variables

– what are variables?

  • A variable is essentially a space in memory that contains data types, names, and literals (data)
  • Variables are the most basic units for storing data in memory

– what is the role of data types?

  • Different data have different types, and different data types will allocate different sizes of space at the bottom.
  • Data type is a guide to how much memory space the program should allocate at run time

– declaration syntax format of variable: data type variable name

– two forms of accessing variables:

  • get: read the specific data saved in the variable
  • set setting: modify the specific data saved in the variable

Variables in java must be declared and then assigned before they can be accessed!

– classification of variables:

Classify according to the location of variable declaration:
Local variables: variables declared in the method body are called local variables
Member variables: variables declared outside the method [within the class] are called member variables

public class VarTest04
{
	//Main method: entrance
	public static void main(String[] args){
		
		int i = 10; //i is a local variable
		//java follows the principle of proximity
		System.out.println(i);

	}

	int i = 100; //i is a member variable
	//System.out.println(i);   java statements cannot be written directly in the class body [except declaring variables]

	public static void doSome(){
		
		//local variable
		int i = 90;
	}
}

– conversion of variable types:

  1. Automatic system conversion:
    When the system automatically converts, the type with less memory space bytes can be automatically converted to the type with more memory bytes.
    (byte/short/char)--int--long,float--double,int--double
  2. Cast: (target type) original type expression

3. Data type

– data types in java include two types: basic data type and reference data type:

  • Basic data type: [four categories and eight categories]
    Type I: integer byte/short/int/long
    Type II: floating point type float/double
    Class III: boolean
    Type 4: character char
  • Reference data type:
    Class I: Class
    The second type: array
    Class III: Interface

The string does not belong to the basic data type, and the string belongs to the reference data type

– space occupied by each of the eight basic data types:

  1. byte 1
  2. short 2
  3. int 4
  4. long 8
  5. float 4
  6. double 8
  7. boolean 1
  8. char 2

Note: the basic data type stores the data value itself in memory, and the reference data type stores the address pointing to the data in memory.

– value range of 8 basic data types:

  1. byte [-128~127]
  2. short [-32768~32767]
  3. int [-2147483648~2147483647]
  4. boolean [true, false]
  5. char [0~65535]

Note: the total number of categories represented by short and char are the same, but char can represent a larger positive integer because char has no negative number.

– default values of 8 basic data types (member variables will be assigned by default without manual assignment, and local variables will not):

  1. byte/short/int/long 0(L)
  2. float/double 0.0(F/D)
  3. boolean false
  4. char '\u0000'

01 character type

public class DataType
{
	public static void main(String[] args){
		
		//Define a variable of char type, named c, and assign the character 'a'
		char c = 'a';
		System.out.println(c);

		//A Chinese occupies 2 bytes, and the char type is exactly 2 bytes
		//Therefore, the char type variable in java can store a Chinese character
		char x = 'in';
		System.out.println(x);

		//char y = 'ab';
		//char k = "z";
	}
}

Native2ascii comes with JDK Exe command, you can convert the text into unicode coding form, enter native2ascii on the command line, enter, and then enter the text to get the unicode code.

java common escape characters:

  1. \ddd: Unicode character represented by octal number
  2. \uxxxx: Unicode character represented by hexadecimal number
  3. \': single quotation mark
  4. \": double quotation marks
  5. \r: Carriage return
  6. \n: Line feed
  7. \f: Page change
  8. \b: One space back

02 integer type

  1. The "integer literal" in the java language is treated as int by default. To treat this "integer literal" as a long type, you need to add I/L after the "integer literal". It is recommended to use uppercase L.
  2. There are three expressions for integer literals in the java language:
    First: decimal (default)
    Second: octal (starting with 0)
    Third: hexadecimal (starting with 0x)
  3. Output in decimal mode
public class DataType
{
	public static void main(String[] args){
		
		int a = 10;
		int b = 010;
		int c = 0x10;

		System.out.println(a); //10
		System.out.println(b); //8
		System.out.println(c); //16

		int i = 123;
		System.out.println(i);

		//456 integer literals are treated as int types and occupy 4 bytes
		//When declared, the x variable is of long type, occupying 8 bytes
		//The literal 456 of int type is assigned to the variable x of long type, and there is type conversion
		//Small capacity can be automatically converted into large capacity, which becomes an automatic conversion mechanism.
		long x = 456;
		System.out.println(x);

		//long z = 2147483648;   Compilation error
		//2147483648 was initially treated as an int type, but this literal exceeds the range of int types.
		long z = 2147483648L;
		System.out.println(z);
		
        long c = 100L;
		int d = (int)c;
		//Conversion from large capacity to small capacity requires forced type conversion and "forced type converter"
		//After the cast, the compilation passed, but the runtime may lose precision.
		/*
			Strong rotation principle:
				Original data: 00000000 00000000 00000000 00000000 00000000 00000000 01100100
				Data after forced conversion: 00000000 00000000 01100100
				Cut the binary on the left directly
		*/

		//If a large capacity int type is converted to a small capacity byte type, an error should be reported theoretically
		byte m = 50;
		/*In the java language, when an integer literal does not exceed the value range of byte, short and char, it can be directly assigned to byte, short and char
		  Variable, the purpose is to facilitate programmer programming*/

		byte n = (byte)128;//-128
	}
}

03 floating point

float: single precision [4 bytes]; Double: double precision [8 bytes, high precision]

SUN prepares more precise types for programmers in the basic SE class library, but this type is a reference data type and does not belong to the basic data type. java.math.BigDecimal

In java programs, SUN provides a huge set of class libraries. java programmers develop based on this set of basic class libraries. So you need to know where the bytecode of java SE class library is:

  • SE class library bytecode: D:\Project_Java\jdk1.8.0_311\jre\lib\rt.jar
  • SE class library source code: D:\Project_Java\jdk1.8.0_311\src.zip

In the java language, all floating-point literals are treated as double by default.

To treat this literal as a float type, you need to add F/f after the literal

Note: double and float are approximate values when they are stored in the internal binary storage of the computer.

public class DataTypeTest01
{
	public static void main(String[] args){
		
		//3.0 is a double literal
		//d is a variable of double type, and there is no type conversion
		double d = 3.0;
		System.out.println(d);

		//5.1 is the literal value of double type, and f is the variable of float type. The conversion from large capacity to small capacity needs to strengthen the type converter
		//Therefore, the following program compilation error.
		//float f = 5.1;

		//Solution:
		float f = (float)5.1; //Cast type

		float f = 5.1f;  //No type conversion
	}
}

04 Boolean

In java, the boolean type has only two values: true and false. Unlike in C, 0 and 1 can represent false and true.

05 data type conversion

About the conversion between basic data types:

  1. Among the eight basic data types, except Boolean, they can be converted to each other

  2. The conversion from small capacity to large capacity is called automatic type conversion, and the capacity is sorted from small to large:
    byte < short < int < long < float < double
    char <

    Note: any floating-point data type, no matter how many bytes it occupies, has a larger capacity than the integer type.
    Char and short can represent the same number of types, but char can take a larger positive integer.

  3. The conversion from large capacity to small capacity is called forced type conversion. The type converter needs to be strengthened before the program can pass the compilation, but the accuracy may be lost in the running stage, so use it with caution

  4. When the face value of the whole number does not exceed the value range of byte, short and char, it can be directly assigned to byte, short and char variables

  5. When byte, short and char are mixed, they are converted into int type before operation.

  6. The mixed operation of multiple data types shall be converted to the type with the largest capacity before operation.

4. Operator

01 arithmetic operator

Note: the remainder operator (%) 10% 4 = 2, 25.3% 12 = 1.3

Spaces are not allowed between unary operators and operands

02 relational operator

>> = < < = takes precedence over = == Priority of

Note: an exact = = comparison cannot be made between floating-point numbers

03 string concatenation operator

When the data on both sides of "+" are numbers, the addition operation must be carried out.

As long as one data on both sides of "+" is a string, string connection operation will be carried out. Moreover, the result of the operation is still a string.

Multiple "+" can appear in an expression. Without adding parentheses, follow the operation from left to right once

public class OperaterTest
{
	public static void main(String[] args){
		
		int a = 10;
		int b = 20;

		System.out.println(10 + 20); //The plus sign here is summation
		System.out.println(10 + 20 + "30"); //From left to right, the first is summation and the second is string connection
		System.out.println("10 + 20 = " + a + b); //All are string connections
		System.out.println(a +" + "+ b +" = "+ (a + b));

		//Reference type String
		//String type is the string type provided by SUN in Java
		int i = 10;
		String username = "abc";
		System.out.println("Login successful, welcome"+ username +"Come back!");
	}
}

04 assignment operator

Note: the extension operator does not change the data type of the original literal value! Therefore, the function of extension operator and basic operator is not exactly the same!

byte b = 10;
//b = b + 5;
//Compilation error: the compiler only checks the syntax, does not run the program, and finds that b+5 is of type int
b = (byte) (b + 5);
b += 5;//sure

byte z = 0;
z += 128;//Equivalent to z = (byte)(z + 128), but not equal to z = z + 128
z += 1000;//z = (byte)(z + 1000), resulting in - 112

5.Scanner keyboard input

Use system The technology of in input data is called standard input and console input. Use system The common way to realize convenient keyboard input is to combine the object of system class Scanner with system In objects.

Scanner s = new Scanner(System.in);

– steps:

  1. The program introduces Java Util package to generate Scanner class objects.
  2. After generating the Scanner object, you can call its own methods for data input.

– method for entering six numeric data types:

  1. nextByte(): byte b = scanner.nextByte();
  2. nextDouble(): double d = scanner.nextDouble();
  3. nextFloat(): float f = scanner.nextFloat();
  4. nextInt(): int i = scanner.nextInt();
  5. nextLong(): long l = scanner.nextLong();
  6. nextShort(): short s = scanner.nextShort();
import java.util.*;
public class ifTest
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);
		System.out.print("How old are you? ");
		int age = in.nextInt();
		System.out.println("Hello,"+"Next year, you'll be "+(age+1));
	}
}

– keyboard input string:

  1. Read in a word and use the next method, ending with a space

    Scanner scanner = new Scanner(System.in);
    String name;
    System.out.print("Enter a string:");
    name = scanner.next();			//The next method uses space and carriage return as separators
    
  2. Read in a line of string and use the nextLine method to output spaces

    Scanner scanner = new Scanner(System.in);
    String name;
    System.out.print("Enter a line of string:");
    name = scanner.nextLine();			//The nextLine method is separated by carriage return
    

3, Program flow control

1. Control selection structure statement

01 if,if...else

– written by:

  1. First:

    if(Boolean expression){
        java sentence;
    }
    
  2. Second:

    if(Boolean expression){
        java sentence;
    }else{
        java sentence;
    }
    
  3. Third

    if(Boolean expression){
        java sentence;
    }else if(Boolean expression){
        java sentence;
    }else if(Boolean expression){
        java sentence;
    }
    
  4. Fourth

    if(Boolean expression){
        java sentence;
    }else if(Boolean expression){
        java sentence;
    }else if(Boolean expression){
        java sentence;
    }else(Boolean expression){
        java sentence;
    }
    

02 switch

– written by:

switch(expression){
    case Expression constant 1:Statement 1;
    case Expression constant 2:Statement 2;
    case Expression constant n:sentence n;
    [default:sentence n+1;]
}
import java.io.*;
class WeekDayTest
{
	public static void main(String args[])throws IOException
	{
		int w;
		System.out.print("Please enter a valid number of weeks(0~6):");
		w = System.in.read()-48;
		switch(w)
		{
			case 0: System.out.println(w +"It means Sunday");
				break;
			case 1: System.out.println(w +"It means Monday");
				break;
			case 2: System.out.println(w +"It means Tuesday");
				break;
			case 3: System.out.println(w +"It means Wednesday");
				break;
			case 4: System.out.println(w +"It means Thursday");
				break;
			case 5: System.out.println(w +"It means Friday");
				break;
			case 6: System.out.println(w +"It means Saturday");
				break;
			default: System.out.println(w +"Is an invalid number!");
		}
	}
}

– note:

  1. Expressions can only be byte, char, short and int types, and cannot use float, booeal, long types and strings.
  2. Curly braces are not required when a case statement includes a multiline run statement.

2. Control loop structure statement

01 for

02 while

03 do...while

3. Change the order of control statements

01 continue

– method of use:

  1. No label: the continue statement is used to end this cycle.

  2. Labeled: at this time, the continue statement skips all the remaining statements of multiple loops in the statement indicated by the label and returns to the condition test part of the statement block indicated by the label for condition judgment.
    To label a program block, simply precede the corresponding program block with a legal Java identifier followed by a colon.

    import javax.swing.JOptionPane;
    public class ContinueLabelTest {
    	public static void main(String args[])
    	{
    		String output = "";
    		rownext:
    		for (int row=1; row <= 5; row++)
    		{
    			output += "\n";
    			for (int column = 1; column <= 10; column++)
    			{
    				if (column > 2*row-1)
    					continue rownext;
    				output += "*";
    			}
    		}
    		JOptionPane.showMessageDialog(null, output, "testing continue with a label",
    		JOptionPane.INFORMATION_MESSAGE);
    		System.exit(0);
    	}
    }
    

02 break

– method of use:

  1. No label: unconditionally terminate the loop statement of the layer where the break is located, and turn to the first statement after it.
  2. Marked: the typical usage is to jump out directly from the inside of the multi-layer loop in which it is located. Just add a label at the beginning of the loop to jump out.

4. Recursion

class factor 
{	
	public long factorial(long n)
	{
		if(n==1)  return 1;
		else  return n*factorial(n-1);
	}
}
public class LoopDGc {
	public static void main(String args[])
	{
		long n = 20l;
		factor a = new factor();
//		long result = a.factorial(n);
		System.out.println(" "+n+" The factorial of is:"+a.factorial(n));
	}
}

4, Array

An array is a collection of elements of the same type.

1. One dimensional array

– statement:

Array name of type []; Or type array name []

Note: Java does not allocate memory space for the array when declaring the array. Therefore, the length of the array cannot be given in square brackets!

– memory request:

The reference variable actually saves the first address of the array or object in the heap memory. The stack reference variable is used in the program to access the array or object in the heap.

int[] a;
a = new int[10];

If you want to free the array memory so that any reference variable does not point to the array object in the heap memory, you can assign the constant null to the array, that is, a = null;

– initialization:

  1. Static initialization:
    Format 1: directly assign values to each element and allocate memory space directly. Data type array name [] = {value 1, value 2, value 3,..., value n}

    int a[] = {1,2,3};
    

    Format 2: use the Scanner system class to enter the value of array elements from the keyboard.

    **Note: * * it is not allowed to declare the array first and then initialize the array with static initialization method in Java program.

  2. Dynamic initialization:

    You need to use the new operator to allocate memory space, which can be initialized at the time of declaration or after declaration.
    Format 1: initialize after specifying the size of the array with the new operator.

    int c[] = new int[3];
    int c[];
    c = new int[3];
    

    Format 2: use the new operator to specify the value of array elements.

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

– for each statement and array:

The for each loop can traverse an array without using subscripts.

public class TestArray{
    public static void main(String[] args){
        double[] myList = {1.9, 2.9, 3.4, 3.5};
        //Print all elements
        for(double element: myList){
            System.out.println(element);
        }
    }
}

2. Two dimensional array

– declaration: type array name [] []; Or array name of type [] [];

– create:

  1. Directly allocate length and size for each dimension:

    int a[][] = new int[2][3];
    
  2. Starting from the first subscript of the high dimension, allocate space for each dimension:

    int b[][] = new int[2][];
    b[0] = new int[3];
    b[1] = new int[5];
    

    A standard matrix is not created at this time.

– initialization:

  1. Dynamic initialization: allocate memory space with new operator, and then assign values to elements.

    int a[][] = new int[2][3];//Define a two-dimensional array with 2 rows and 3 columns
    a[0][0] = 33;
    
  2. Dynamic initialization: directly assign values to each element, and allocate memory space for the array while declaring and defining the array.

    int a[][] = {{2,3}, {1,3}, {2,3}}
    

5, Java classes and objects

1. Object oriented programming

Encapsulation:

Combine the attributes and services of the object into a system unit, and hide the internal details of the object as much as possible.
Class is a group of objects and general descriptions with the same properties and behaviors. It is a software implementation of encapsulation.

Inheritance:

It is a mechanism to create new classes from existing classes. It is the cornerstone of object-oriented programming.
Note: Java only supports single inheritance, while C + + supports multiple inheritance.

Polymorphism:

It is realized by method overloading, method refactoring and abstract class technology. Polymorphism refers to multiple ways.

Message:

Objects interact with each other through messages.

2. Class description

Definition of class 01

class Class name{
    [Member variable];
    [Member method];
}

Note: the member variables of a class must be placed in the class body, but cannot be included in a method.

[public] [abstract/final] class name {class body}

– class modifiers:

  1. Public public class: the class can be used by any class in the package, that is, the class is open. Generally, the class containing the main method is defined as a public public class, and the name of the public class is used as the file name of the source file.
  2. Abstract abstract class: an abstract class cannot instantiate an object and can only be inherited.
  3. Final final class: indicates that this class cannot be inherited.

Note: Java does not care about the order in which modifiers appear, but final and abstract cannot modify a class at the same time.

02 access control of member variables

The declaration of a member variable must be placed in the class body, usually before the member method. The variable declared in the method is not a member variable, but a local variable of the method.
Format of member variable: [access controller] variable type variable name [= initial value];

– access control characters:

  1. public modifier: member variables can be accessed by any class.
  2. private modifier: member variables can only be accessed by the class's own methods.
  3. protected modifier: member variables can be accessed by this class, subclasses of the class (under different packages) and other classes of the same package.
  4. friendly default access permission: members can be accessed by the class itself and classes in the same package.

03 member method

[Method modifier] Method return value list method name([Formal parameter list]){
    [Local variable list;]
    [Statement block;]
}

**When declaring a local variable, you should pay attention to: * * no modifier can be added before the variable type; If the variable is not assigned at the time of declaration, the local variable has no default value.

class Rectangle{
	double width,height;
	Rectangle(double w, double h){ //Construction method of class
		width = w; height = h;
	}
	double area(){					//Method for calculating rectangular area
		return width * height;
	}
}
public class RectangleTest {
	public static void main(String args[])
	{
		double s;
		Rectangle myRect = new Rectangle(20, 30);  //Create object myRect
		s = myRect.area();			//Call the object method area to calculate the rectangular area
		System.out.println("Rectangle The area is:"+s);//Output area
	}
}

04 member variables, local variables and final

– difference between local variables and member variables:

  1. Member variables belong to classes, while local variables are variables defined in methods or parameters of methods.
    Member variables can be modified by modifiers such as public, private and static, while local variables cannot be modified by access control characters and static.
  2. Member objects are stored in heap memory, and local variables are stored in stack memory.
  3. Member variables exist with the creation of the object, and local variables are generated with the call of the method and disappear automatically with the end of the method call.
  4. If the member variable is not assigned an initial value, it will be assigned with the default value of the corresponding type; Local variables will not be assigned automatically, and can be used only after they are explicitly assigned.

– final variable:

The member variable modified by final is actually a constant, and its value cannot be changed during the running of the program.

final double PI=3.14159

Constant names generally use uppercase letters.

3. Creation and use of objects

In Java, the creation, use and release of objects are called the life cycle of objects.

01 creation of objects

Including: object declaration, object instantiation and object initialization.

**Object declaration: * * consists of class name and object name.
**Object instantiation: * * when declaring an object, no storage space is allocated to the object. Object instantiation can complete the space allocation of objects. Completed by the new operator.
**Object initialization: * * completed by the constructor.

The new operator returns a reference. An object reference is actually a reference variable that points to the first address of the memory where the object is located.

02 use of objects

– general use of objects:

  1. Reference the member variable of the object through the object: object name Variables;
  2. Call the member method of the object through the object: object name Method name ([parameter list]);

– objects as array elements:

When creating an object array, first declare the array and allocate memory space to the array with the new operator, and then initialize each object element of the array.

class Node{  //Definition of node class
	private int data;   		//The object itself is the concept of an address
	private Node next;
	void setData(int x)
	{
		data = x;
	}
	int getData()
	{
		return data;
	}
	Node getNext()
	{
		return next;
	}
	void setNext(Node x)
	{
		next = x;
	}
}
public class ObjArray {			//Main class
	public static void main(String args[]) {
		Node x[] = new Node[3];					//Create 3 node objects as array elements
		
		int i;
		for(i = 0; i < x.length; i++)			//Initialize object array elements
			x[i] = new Node();
		for(i = 0; i < x.length; i++)			//Assign values to node data and form a linked list
		{
			x[i].setData(i);
			if(i < x.length-1)  x[i].setNext(x[i+1]);
		}
		
		Node start = new Node();				//Use start to output the value of the midpoint in the linked list in turn
		start = x[0];
		System.out.println(start.getData());
		while(start.getNext()!=null)
		{
			start = start.getNext();
			System.out.println(start.getData());
		}
	}
}

**– object as member variable of class: * * class member contains objects of other classes.

03 anonymous object

After an object is created, when calling the member method of the object, you can also directly call the method of the object without defining the name of the object. Such an object is called an anonymous object.

Person p1 = new Person();
p = new Person();
p.speak();

Can be rewritten as:

new Person().speak();

Use of anonymous objects:

  1. If only one method call is required for an object
  2. Pass an anonymous object as an argument to a method call

4. Construction method of class

When constructing a method, it is a special method. Its name must be exactly the same as the class name of its class. There is no return value and no void. And:

  • Constructor can only be called by new operator.
  • The constructor cannot be inherited, but the subclass can call the constructor of the parent class.
  • Constructors are not allowed to specify return value types or return values, and void cannot be used
  • Construction methods can be overloaded.

If there is no constructor defined in the class, the compiler will automatically create a default constructor without parameters. [nonparametric construction method]

Initial default value of instance variable of class:
Boolean: false
Character type: '\ u0000'
Integer: 0
Floating point: 0.0
Reference: null

this reference*

Refers to the reference to the object itself of the class where this belongs.

1. Use this to refer to member variables:

class Demo{
    double x,y;
    Demo(double x, double y){this.x = x; this.y = y;}
    double ave(){return (x+y)/2;}
}
class TestThis1{
    public static void main(String args[]){
        Demo s = new Demo(3,4);
        System.out.println(s.ave());
    }
}

In a method, if a method parameter has the same name as a member variable of a class, this should be explicitly used when accessing the member variable of the class

2. Use this in the construction method to call the general method:

class Demo{
    int x,y;
    Demo(int a, int b){
        x = a;
        y = b;
        this.sort(a,b);  //this can not be written here
    }
    void sort(int a, int b)
    {
        int t;
        if(x < y){t = x; x = y; y = t;}
    }
}
class TestThis2{
    public static void main(String args[]){
        Demo m1 = new Demo(12,20);
        System.out.println(m1.x+" "+m1.y);
    }
}

3. calling another construction method in a construction method:

this keyword must be written in the first line of the construction method!

class Cylinder{
	private double radius;
	private int height;
	private double pi = 3.14;
	String color;
	public Cylinder() {
		this(2.5, 5, "orange");	//Call another constructor. this call needs to be placed on the first line
		System.out.println("The parameterless constructor method was called");
	}
	public Cylinder(double r, int h, String str) {
		System.out.println("A parameter constructor was called");
		radius = r;
		height = h;
		color = str;
	}

	public void show() {
		System.out.println("The radius of the cylinder bottom is:"+radius);
		System.out.println("The height of the cylinder is:"+height);
		System.out.println("The cylinder color is:"+color);
	}

	double area() {
		return pi*radius*radius;
	}
	double volmn() {
		return area()*height;
	}

}

public class TestThis3 {
	public static void main(String args[]) {
		Cylinder c = new Cylinder();
		System.out.println("Cylinder bottom area:"+c.area());
		System.out.println("Cylinder volume:"+c.volmn());
		c.show();
	}
}

Operation results:

A parameter constructor was called
 The parameterless constructor method was called
 Cylinder bottom area: 19.625
 Cylinder volume: 98.125
 Radius of cylinder bottom: 2.5
 Height of cylinder: 5
 Cylinder color: Orange

5.static variable and static method

The member variable decorated with static is called the static variable of the class and is not regarded as the member variable of the instance object.

Static variables are owned by the class and are directly referenced by the class name.

01 static variable

A static variable is a public storage unit. When an object of any class accesses it, it gets the same value. Similarly, when an object of any class modifies it, it is also operating on the same memory unit.

– use format of static variables:

Class name Static variable name; Or object name Static variable name;

If a class contains static variables, the static variables must be independent of member methods.

02 static method

Static methods are essentially methods belonging to the whole class, rather than methods without static modifier. They are methods belonging to a specific object and become instance methods.

– use format of static method:

Class name Static method name (); Or object name Static method name ();

This or super cannot be used in static methods. Because they all represent the concept of object, this represents the object of this class, and super represents the concept of upper parent class.
Static methods can only access static member variables or call static member methods.

6. Object initialization process

class Bird{
	public Bird(String name) {
		System.out.println("Bird "+name+" 3");
	}
	void feed() {
		System.out.println("feed()4");
	}
}

class Animal{
	Bird b1 = new Bird("HL");
	static Bird b2 = new Bird("static HL");		//Static instance variable
	static {									//Static initializer, static code block
		b2.feed();
	}
	public Animal() {
		System.out.println("Animal");
	}
	public Animal(String name) {
		System.out.println("Animal "+name+" 2");
	}
}

public class Insects extends Animal{
	public Insects(String name) {
		super(name);
		System.out.println("insects "+name+" 1");
	}
	public static void main(String args[]) {
		Insects a1 = new Insects("ant");
		Insects a2 = new Insects("ant2");
	}
}

Operation results:

Bird static HL 3		Static code is executed only once
feed()4
Bird HL 3				establish Animal Member variables in class b1 Results
Animal ant 2			a1 of Insects Construction method execution
insects ant 1
Bird HL 3				object a2 Before the construction method is executed, execute b1 Static code is no longer executed
Animal ant2 2
insects ant2 1

The first step is to execute the static code of the parent class in the source code, including the static variable declaration and the code block modified by static, and only execute it once.
The second is the creation of parent class b1.
Then there is the construction method of objects a1 and a2 of class inserts.

In addition, the subclass Insects not only has the properties and member methods of the parent class, but also inherits the parameterless constructor of the parent class when it does not define its own constructor.

Comparison between static initializer and construction method:

  1. The constructor initializes each newly created object, while the static initializer initializes the class itself.
  2. The construction method is to create a new object with the new operator, which is automatically called by the system; The static initializer can not be called by the program. It is executed by the system call when the class is loaded into memory.
  3. How many new objects are created with the new operator, and how many times the constructor is called; However, the static initializer is only executed once when it is loaded.
  4. Unlike construction methods, static initializers are not methods, but code blocks.

7. Membership method

01 method calling and parameter passing

– parameter passing of Java language:

  1. Parameter passing of basic data type: Value Passing call
  2. Parameter passing of reference type: address passing reference call

– form of method call:

  1. The general form of calling object member methods: object name Method name ([actual parameter list]);
  2. Static methods belong to class methods. The general form of call: class name Method name ([actual parameter list]);

02 method overload

Note: methods cannot distinguish overloaded methods by return value type!

public class OverLoadDemo {
	void overload() {
		System.out.println("First reload!");
	}
	
	void overload(String str) {
		System.out.println("Second reload!"+str);
	}
	
	void overload(String str1, String str2) {
		System.out.println("Third reload!"+str1+str2);
	}
	
	public static void main(String args[]) {
		OverLoadDemo strdemo = new OverLoadDemo();
		strdemo.overload();
		strdemo.overload("Java");
		strdemo.overload("Love","China");
	}
}

03 final method and abstract method

1. final method:

The final method can be inherited and used by subclass methods, but it cannot be modified or redefined in subclasses.

2. abstract abstract method:

Abstract method refers to the method without method body, that is, the method without implementation. The class containing abstract method becomes abstract class.

6, Class inheritance and interface

1. Class inheritance

– creation of subclasses:

[Modifier ] Subclass name extends Parent class name{
	Class body
}

In the definition of a class, if extensions is not used, the class inherits the Object class by default.

**Note: * * the Java program calls the constructor of the parent class before running the constructor of the child class. If the parent class provides a parametric construction method, it does not provide a construction method without reference, and it will generate syntax errors when calling the substructure of the subclass in the main class. Solution: add a formal parameterless constructor to the parent class: public Person() {}.

2. Hiding and reconstruction

01 hiding of member variables

When the subclass hides the member variable of the parent class with the same name, the subclass actually has two member variables with the same name. To reference a member variable with the same name in the parent class:
super. Member variable name; Or parent class name Member variable name// Applies only to static variables

02 override of member methods

– difference between overload and override:

Method overloading means that there are several methods with the same name but different parameters in the same class. Different versions of methods with the same name can be called by using different parameter numbers and parameter types;
Method override refers to reconstructing a member method of the parent class in the subclass with the same method name, method type and parameters as those in the parent class.

The non private method of the parent class will be automatically inherited by the child class.

– the following three conditions must be met for the subclass to override the parent method:

  1. Identical method name
  2. Identical parameter list
  3. Return values of exactly the same type

The java interpreter will search along the inheritance chain, select the correct method to bind to the current object, and produce different response results.

3. Abstract class

The classes described by the keyword abstract are abstract classes, which usually contain abstract methods. Abstract method refers to a method with access modifier, return value type, method name and parameter list, but no method body and no curly brackets containing the method body.

When a subclass inherits an abstract class, it must override the sampling method of its parent class and give a specific definition.

Construction method, static method and private method cannot become sampling method. new cannot be used to create instances of abstract classes. Abstract classes can only be used to derive subclasses from parent classes.

When a subclass inherits an abstract class, if it does not implement all the abstract methods of the parent class, the subclass is still an abstract class.

abstract class Graphics{
	abstract void parameter();  	//Parameter processing
	abstract void area();			//Area treatment
}
class Rectangle extends Graphics{
	double h,w;
	Rectangle(double u, double v){h = u; w = v;}
	void parameter() {
		System.out.println("Rectangle height is:"+h+", Rectangle width is:"+w);
	}
	void area() {
		System.out.println("Rectangular area is:"+(h*w));
	}
}
class Circle extends Graphics{
	double r;
	String c;
	Circle(double u, String v){r = u; c = v;}
	void parameter() {
		System.out.println("Radius of circle:"+r+", Color of circle:"+c);
	}
	void area() {
		System.out.println("Circular area:"+(Math.PI*r*r));
	}
}
public class Exam {
	public static void main(String args[]) {
		Rectangle rec = new Rectangle(2.0,3.0);
		Circle cir = new Circle(4.0,"Red");
		Graphics[]g = {rec, cir};
		for(int i = 0; i < g.length; i++)
		{
			g[i].parameter();		//Start different parameter methods according to different object types
			g[i].area();			//Start different area methods according to different object types
		}
	}
}

Abstract classes are used to specify the method headers of a set of methods that their subclasses must have. Using abstract classes and abstract methods can separate the design of method headers from the implementation of methods, which is conducive to controlling the complexity of programs.

4. Interface

Interface is a set of abstract methods and constants, which can be considered as a special abstract class with only constants and abstract methods. Interface plays a role called interface between method protocol and method implementation. The interface specifies that the method name, parameter type, number of parameters and method return type in method implementation must be consistent with those specified in method protocol. Therefore, there is no inheritance relationship between subclasses and parent classes between classes and interfaces. A class can implement multiple interfaces.

01 interface definition and class definition

– definition of interface:

[public] interface Interface name [extends Parent interface list]
{
    [public static final] Type constant name = value;
    [public abstract] Return value type interface method name(Formal parameter table);
}

The method of the interface defaults to the public abstract attribute; The default public static final attribute of variable members of the interface.

– class definition of interface:

[Class access control modifier] class Class name [extends Parent class name] implements Interface list
{Class body}

The class implementing the interface must implement each method in the interface, including the method defined in the parent interface of the interface. If an interface method is not implemented, the class must be defined as an abstract class, otherwise compilation error occurs.

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
interface Shape {
	public abstract double area();
}
class Circle implements Shape{
	protected double radius;
	public Circle() {setRadius(0);}
	public Circle(double r) {setRadius(r);}
	public void setRadius(double r) {radius = (r>0?r:0);}
	public double getRadius() {return radius;}
	//Implement the area method of the interface Shape
	public double area() {return Math.PI*radius*radius;}
}
class Triangle implements Shape{
	protected double x,y;
	public Triangle() {setxy(0,0);}
	public Triangle(double a, double b) {setxy(a,b);}
	public void setxy(double x, double y) {this.x = x; this.y = y;}
	public double getx() {return x;}
	public double gety() {return y;}
	//Implement the area method of the interface Shape
	public double area() {return x*y/2;}
}
public class shapeTest {
	public static void main(String args[]) {
		Circle c = new Circle(7);
		Triangle t = new Triangle(3,4);
		String output = "";
		DecimalFormat p2 = new DecimalFormat("0.00");
		//Output the area of the instance circle and triangle in the dialog box
		output += "\n Radius"+c.getRadius()+"Area of circle:"+p2.format(c.area());
		output += "\n Bottom"+t.getx()+",Gao Wei"+t.gety()+"Triangle area:"+p2.format(t.area());
		JOptionPane.showMessageDialog(null, output, "Interface implementation and use demonstration",
				JOptionPane.INFORMATION_MESSAGE);
		System.exit(0);
	}
}

java. Jooptionpane class in AWT package is used to create basic dialog box:

  1. showMessageDialog is used to create a message dialog box that displays only output strings or results
  2. showInputDialog is used to create a dialog box for inputting data, displaying prompt information and a text input box
  3. showConfirmDialog is used to create a confirmation dialog box, prompt the user with a simple "yes or no" question, and ask the user to confirm

The above static method generally has four parameters:

  1. If there is no parent component of the dialog box, it will be set to null, and the dialog box will be displayed in the middle of the screen
  2. Messages displayed in the dialog box
  3. Title of the dialog box
  4. Message type of dialog box
    • JOptionPane.ERROR_MESSAGE displays an error message with the icon ''-“
    • JOptionPane.INFORMATION_MESSAGE displays information with the icon "i"
    • JOptionPane.WARNING_MESSAGE displays a warning message with the icon "!"
    • JOptionPane.QUESTION_MESSAGE displays the problem message with the icon "
    • JOptionPane.PLAIN_MESSAGE displays standard messages without icons

02 Java 8 interface extension method

Java 8 allows you to add a non abstract method to an interface

interface Formula{
    double calculate(int a);
    default double sqrt(int a){
        return Math.sqrt(a);
    }
}

In addition to the calculate method, the Foemula interface also defines the sqrt method. The subclass implementing the Formula interface only needs to implement one calculate method, and the default method sqrt will be used directly on the subclass.

5. Generics

The advantage of Generic Structure is that it can check type safety at compile time, and all coercions are automatic and implicit, which improves the reuse rate of code.

The statement is as follows:

class name<Generic type variable>

Generic types can only be class types (including custom classes), not simple types.

class Gen<T>{
	private T ob;				//Defining generic member variables
	public Gen(T ob){			//Parameters use generic member variables
		this.ob = ob;
	}
	public T getOb() {			//The return value type is generic
		return ob;
	}
	public void setOb() {
		this.ob = ob;
	}
	public void showType() {
		System.out.println("T The actual type of is:"+ob.getClass().getName());
		//Using system method
	}
}

public class GenDemo {
	public static void main(String args[]) {
		//Defines an Integer version of the generic class Gen
		Gen<Integer> intOb = new Gen<Integer>(88);
		intOb.showType();			//Using methods in generic classes
		int i = intOb.getOb();		//Using methods in generic classes
		System.out.println("value="+i);
		System.out.println("---------------------");
		//Defines a String version of the generic class Gen
		Gen<String> strOb = new Gen<String>("Hello Gen!");
		strOb.showType();			//Using methods in generic classes
		String s = strOb.getOb();		//Using methods in generic classes
		System.out.println("value="+s);
	}
}

Keywords: Java Back-end

Added by QSDragon on Tue, 01 Feb 2022 05:01:56 +0200