Java study notes [continuous update]

Java study notes [continuous update]

A simple java program is as follows:

class Sakura

{

public static void main(String[] arges)

{

system.out.println("Hello World");

system.out.print("hahaha");

}

}

1. The appearance of the main function can ensure the independent operation of a class

2. In the java program, the difference between pirnt and println is whether to print a carriage return and line feed after println outputs a line, but print does not!

Let's take the suffix 123.java as an example to analyze the java source file:

The address where we store 123.java is at D:/day1>

At this time, we only need to enter javac 123.java, and a class file will be generated immediately in the specified folder, as follows:

I found out that the prefix name of the class file is Sakura, which means that the name of the class is customized. Here, let me explain

javac->Originally named java c ompilation (java language editor), if the source file is compiled through javac, the specified class source file will be generated, and java can only run the class source file

How do we run this file?

Enter java Sakura.class/java Salura in D:\day1>, the running result is as follows:

The java command is equivalent to executing the class file, and here we can omit the .class suffix, because java can only execute the source file of the class, so there is no need to specify this point!

Java is also equivalent to starting the virtual machine file, to execute the class file, go to the specified folder to execute the .class, and make it into the memory

Common mistakes made by beginners:

1.

Found a problem, 123.java is a text file

You can also query through cmd->dir and find that the file is a txt file

So to set the file:

Click OK again!

2. I will run it wherever the running file is. In fact, the simple explanation is where the class file is and where we run it!

3. When we want to execute the file in any path, we should tell the path where the file is executed, and Windows will help us find the executable file

 The binary of a negative number is equal to the binary inverse of the positive number of this number +1. For any negative number, the highest bit of the binary is 1.

How to convert decimal to binary:

Divide the integer part of the decimal number by 2 and write down the remainder until the quotient is 0.

Such as N=117D (D stands for decimal number)

117/2=58(1)

58/2=29(0)

29/2=14(1)

14/2=7(0)

7/2=3(1)

3/2=1(1)

1/2=0(1)

N=1110101B (B represents a binary number)

BF3CH (H stands for hexadecimal)

2324O (O stands for octal)

Shifting a few places to the left is equal to multiplying by the power of 2, and shifting a few places to the right is equal to dividing by the power of 2.

ctrl+c end console printing

2017.8.11

1. Special circumstances:

The function has no specific return value, at this time, the return is directly ended with a semicolon

How to reflect the return value type, because there is no specific value, it is not possible to write specific data types

In java, only one keyword can be used to represent this situation, the keyword is void

Summary: In the absence of a specific return value, the return value type is represented by void!

2. Note: If the return value type is void, then the return statement in the function can be omitted.

2017.8.15

The relationship between class and object:

A class is a description of a thing, and an object is an instance of that thing

Object-oriented: Use java language to describe things in real life, which are embodied in the form of classes

How to describe it? The description of things usually only pays attention to two aspects: one is the attribute, the other is the behavior, as long as the attribute and behavior of the thing are clearly defined and defined in the class!

The relationship between class and object:

Class: Description of things

Object: an instance of this kind of thing, created by new in the java language!

2017.8.16

Constructor: Construct a function that is called when the object is created, and can initialize the object

If a constructor has not been defined in a class, then there will be a default empty parameter constructor in the class

If the specified constructor is defined in the class, then the default constructor in the class is gone

Constructor: When an object is created, the corresponding constructor is called to initialize the object

General function: After the object is created, it is called when the function function is needed

Constructor: When the object is created, it will be called only once

General function: After the object is created, it can be called multiple times

When is the constructor defined?

When describing a thing, some content that the thing already has, these contents are defined in the constructor

There can be multiple constructors for targeted initialization of different objects

Multiple constructors are embodied in the form of overloading in the class

When the member variable and the local variable have the same name, the keyword this can be used to distinguish

this: represents the object, which object does it represent? Current object

this is the reference of the object to which the function belongs

Simply put: which object calls the function where this is located, and this represents which object

Features of static:

1.static is a modifier, used to modify members

2.Static modified members are shared by all objects

3.Static takes precedence over the existence of objects, because static members already exist with the loading of the class

4. The static modified member has one more calling method, which can be directly called by the class name, the class name. Static variable

5.Static modified data is shared data, and the storage in the object is unique data

The difference between member variables and static variables:

1. The life cycles of the two variables are different

Member variables exist as the object is created, and released as the object is recycled

Static variables exist as the class is loaded, and disappear as the class disappears

2. Different calling methods:

Member variables can only be called by the object;

Static variables can be called by the object, and can also be called by the class name

3. Different aliases:

Member variables are also called instance variables

Static variables are called class variables

4. The data storage location is different

The member variable data is stored in the object in the heap memory, so it is also called the unique data of the object

Static variable data is stored in the static area of the method area (shared data area), so it is also called the shared data of the object

Precautions for static use:

1. Static methods can only access static members, (non-static can access both static and non-static)

2. The this or super keywords cannot be used in static methods

3. The main function is static

public: because the permissions must be the largest

static: If you don't need an object, you can call it directly with the name of the class to which the main function belongs

void: The main function has no specific return value

main: function name, not a keyword, just a fixed name recognized by jvm

String[] args: This is the parameter list of the main function, which is an array type parameter, and the elements are all string types

When to use static:

1. Static variables;

When the values of the member variables in the analysis object are the same, then this member can be statically modified

As long as the data is different in the object, the data held by the object must be stored in the object, which is non-static

If it is the same data, the object does not need to be modified, it only needs to be used instead of stored in the object, and defined as static

2. Static function:

Whether the function is statically decorated, just refer to it, that is, whether the function of the function has access to the unique data in the object

To put it simply, from the source code to see whether the function needs to access non-static member variables, if necessary, the function is non-static

If you don t need it, you can define the function as static or non-static.

But non-static needs to be called by the object, and only the creation of the object calls the non-static

There is no way to access unique data, the creation of the object is meaningless

Static code block:

Executed with the loading of the class, and only once

effect:

Used to initialize the class

Construct code block:,

All objects can be initialized, and the constructor is to perform targeted initialization for the corresponding objects

 8.18

The methods of this class are static, so this class does not need to create objects. In order to ensure that other members are not allowed to create objects of this class, the constructor can be privatized

When the same configuration information object must be used for multiple programs, the uniqueness of the object needs to be guaranteed.

How to ensure the uniqueness of the object?

1. Other programs are not allowed to create objects of this type with new

2. Create an instance of this class in this class

3. Provide a method for other programs to obtain the object

step:

1. Privatize this type of constructor

2. Create an object of this class in this class through new

3. Define a public method to return the created object

8.20

Benefits of inheritance:

1. Improved code reusability

2. Let the relationship between the class and the class have provided a premise for the third characteristic polymorphism

Single inheritance is supported in java, and multiple inheritance is not directly supported. However, the multiple inheritance mechanism in C++ has been improved, and it has become multiple implementations in java. One class can implement multiple interfaces

Single inheritance: a subclass can only have one direct parent class

Multiple inheritance: A subclass can have multiple direct parent classes (not allowed in java, for improvement)

Not directly supported, because multiple parent classes have the same members, which will cause call uncertainty

Java supports multiple (multiple) inheritance

C inherits B, B inherits A, there will be an inheritance system

When using an inheritance system,

1. Check the top-level classes in the system to understand the basic functions of the system

2. Create the most subclass object in the system to complete the use of functions

When to define inheritance?

When there is an ownership relationship between a class and a class, inheritance is defined, xxx is one of yyy, xxx extends yyy

Ownership is: is a relationship

When the members and local variables of this class have the same name, use this to distinguish

When the member variables in the child parent class have the same name, use super to distinguish the parent class

The usage of this and super are very similar

this: represents a reference to this class of object

super: represents a super class space

Member function:

When the member function is exactly the same in the child parent class, the function of the child class will be run. This phenomenon is called coverage operation, which is the characteristic of the function in the child parent class

Two characteristics of the function:

1. Overloading: in the same class

2. Overwrite: In the sub-category, overwrite is also called overwrite and overwrite. override

Coverage notes:

1. When the subclass method overrides the parent class method, the subclass's permissions must be greater than or equal to the parent's permissions

2. Static can only cover static, or be covered by static

When to use the overwrite operation

But when a class is extended to a subclass, the subclass needs to retain the function declaration of the parent class

But to define the unique content of the function in the subclass, use the overwrite operation to complete

2017.8.21

The characteristics of the constructor in the parent class:

When the subclass constructs the object, it is found that when the subclass constructor is accessed, the parent class is also running.

why?

The reason is that there is a default implicit statement in the first line of the subclass's constructor: super()

The instantiation process of the subclass: all the constructors in the subclass will access the empty parameter constructors in the parent class by default

Why do you need to access the constructor in the parent class when the subclass is instantiated?

That's because the child class inherits the parent class and obtains the content (attributes) of the parent class, so before using the parent class content, you must first see how the parent class initializes its own content.

So when the subclass constructs the object, it must access the constructor in the parent class

Why do you complete this necessary action? The super() statement is added to the constructor of the subclass

If the empty parameter constructor is not defined in the parent class, then the constructor of the subclass must use super to specify which constructor in the parent class is to be called. At the same time, if the constructor of this class is called using this in the subclass constructor,

Then super is gone, because super and this can only define the first line, so there can only be one, but it can be guaranteed that there will definitely be other constructors in the subclass to access the constructor of the parent class

Note: The super statement must be defined in the first line of the subclass constructor, because the initialization of the parent class must be completed first

 

When the content of the parent class is initialized by super, the member variables of the subclass are not displayed and initialized. After the super() of the parent class is initialized, the member variables of the subclass are displayed and initialized.

 

An object instantiation process:

Person p=new Person();

1. JVM will read the Person.class file under the specified path and load it into memory

And will load the parent class of Person first (if there is a direct parent class)

2. Open up space in the heap memory and allocate addresses

3. And in the object space, perform default initialization operations on the properties of the object,

4. Call the corresponding constructor to initialize

5. In the constructor, the first line will first call the constructor in the parent class to initialize

6. After the parent class is initialized, display and initialize the properties of the child class

7. Then carry out the specific initialization of the subclass constructor

8. After initialization, assign the address value to the reference variable

Disadvantages of inheritance: breaking the encapsulation

final keyword:

1.final is a modifier that can modify classes, methods, and variables

2. The final modified class cannot be inherited

3. The final modification method cannot be overwritten

4. The final modified variable is a constant and can only be assigned once

Why use final to modify variables? In fact, if only one data is fixed in the program, then this data can be used directly, but this is poor in readability, so it gives the data a name

And the value of the variable name cannot be changed, so the final fix is added

Writing specification: all letters of the constant are capitalized, multiple words, connected with _ in the middle

The characteristics of abstract classes:

1. When the method is only declared but not implemented, the method is an abstract method and needs to be modified by abstract. The abstract method must be defined in an abstract class, which must also be modified by abstract

2. Abstract classes cannot be instantiated, why? Because calling abstract methods is meaningless

3. The abstract class must have its subclass covering all abstract methods before the subclass can be instantiated, otherwise, this subclass is still an abstract class

 

1. Does an abstract class have a constructor?

Yes, it is used to initialize subclass objects.

2. Can an abstract class not define abstract methods?

Yes, but it is rare. The purpose is to prevent this class from creating objects. The adapter object of AWT is this class. Usually the methods in this class have method bodies, but they have no content.

3. What keywords cannot coexist with abstract keywords?

not private

static does not work

final not

4. The similarities and differences between abstract classes and general classes

Similarities: Abstract and general classes are used to describe things, and both have internal members.

difference:

  • General classes have enough information to describe things, but abstract classes may not have enough information
  • General classes cannot define abstract methods, only non-abstract methods. Abstract classes can define abstract methods and non-abstract methods.
  • General classes can be instantiated, abstract classes cannot be instantiated

5. Is the abstract class a parent class?

Yes, because the subclass needs to override its method before it can be instantiated

 

When the methods in the abstract class are abstract, then the abstract class can be defined and represented in another form, which is the interface

The keyword used to define the interface is not class, but interface

For members commonly used in interfaces, and these members have fixed modifiers

1. Global constants: public static final

2. Abstract method: public abstract

It is concluded that the members in the interface are all public permissions

There is an inheritance relationship between classes and an implementation relationship between classes and interfaces

The interface cannot be instantiated, it can only be instantiated by the subclass that implements the interface and covers all the abstract methods in the interface, otherwise the subclass is an abstract class

A class can implement multiple interfaces while inheriting another class

The emergence of interfaces avoids the limitations of single inheritance

There is an inheritance relationship between the interface and the interface, and the interface can inherit multiple

 

Similarities and differences between abstract classes and interfaces:

Same point:

Are drawn continuously upwards

difference:

1. Abstract classes need to be inherited, and only single inheritance, interfaces need to be implemented, and multiple implementations are possible

2. Abstract methods and non-abstract methods can be defined in abstract classes. After subclasses inherit, non-abstract methods can be used directly. Interfaces can only define abstract methods, which must be implemented by subclasses.

3. Inheritance of abstract classes: is a relationship, defining the basic common content of the system

   The realization of the interface is like a relationship, in the definition of additional functions of the system

2017.8.24

The polymorphism of objects simply means that an object corresponds to different types

The manifestation of polymorphism in the code:

The reference of the parent class or interface points to the object of its subclass

The benefits of polymorphism:

Improve the scalability of the code, the code defined in the previous period can use the content of the later period

Disadvantages of polymorphism:

The content defined in the previous period cannot use (call) the unique content of the later subclass

The premise of polymorphism:

1. There must be a relationship, inheritance, and realization

2. To have coverage

For example: cats belong to animals, at this time we define Animal a=new cat();, automatic type promotion, the cat object promotes the animal type, but the unique function cannot be accessed, the function is to restrict the access to the unique function

Professionally speaking, it is upward transformation, hiding from sub-types, so there is no need to use the unique methods of sub-types

If you still want to use the specific functions of a specific animal cat, you can downcast the object, Cat c=(Cat)a;

Downcasting is to use unique methods in subclasses

Note: For transformation, subclass objects are making transformational changes from beginning to end

Instanceof, used to determine the specific type of the object, can only be used to determine the type of reference data, usually used to determine the robustness before downcasting

The characteristics of members during polymorphism:

1. Member variables:

When compiling, refer to whether there is a member variable called in the class to which the reference variable belongs, yes, the compilation passed, no, the compilation failed

At runtime, refer to whether there is a member variable called in the class to which the reference variable belongs, and run the member variable in the class to which it belongs

Simply put, compile and run refer to the left side of the equal sign, oh! As understanding

2. Member functions:

When compiling, refer to whether there is a function called in the class to which the reference variable belongs, yes, the compilation passed, no, the compilation failed

At runtime, it refers to whether there is a function called in the class to which the object belongs

Simply put, look at the left for compilation and look at the right for running

3. Static function:

When compiling, refer to whether there is a static method called in the class to which the reference variable belongs

At runtime, refer to whether there is a static method called in the class to which the reference variable belongs

Simply put, compile and run are all on the left

In fact, for static methods, objects are not needed, just call them directly with the class name

Features of internal access:

1. The inner class can directly access the members in the outer class

2. To access the internal class from the external class, an object of the internal class must be established

One for class design

When analyzing things, it is found that there are still things in the description of the thing, and this thing is still accessing the content of the described thing. At this time, the other things are defined as internal classes to describe

Directly access the members of the inner class in the outer class

If the internal is static, it is equivalent to an external class

If the inner class is static, the members are static

If static members are defined in the inner class, the inner class must also be static

Why can the inner class directly access the members in the outer class?

That's because the inner class holds a reference to the outer class, the name of the outer class.this

For example:

1 class Outer 2 { 3 int num=3; 4 class Inter 5 { 6 int num=4; 7 void show() 8 { 9 int num=5; 10 System.out.println(num);//5 11 System.out.println(this.num);//4 12 System.out.println(Outer.this.num);//3 13} 14} 15 void method() 16 { 17 new Inter().show(); 18} 19} 20 21 class Interclass 22 { 23 public static void main(String[] args) 24 { 25 new Outer().method(); 26} 27} Copy code

 Internal classes can be stored in local locations

The inner class can only access the local variables modified by final in the local position.

2017/8/25

Anonymous inner class: shorthand for inner class

There must be a prerequisite, the inner class must inherit or implement an outer class or interface

An anonymous inner class is actually an anonymous subclass object

Format: new parent class or interface () {subclass content}

One of the usual usage scenarios:

When the function parameter is an interface type, and there are no more than 3 methods in the interface, you can use the anonymous inner class as the actual parameter to pass

for example:

1 class Fu 2 { 3 int num=9; 4 { 5 System.out.println("Fu");//1 6} 7 Fu() 8 { 9 super(); 10//Display initialization 11//Construction code block initialization 12 System.out.println("Fu constructor run");//2 13 show(); 14} 15 void show() 16 { 17 System.out.println("Fu show..."+num); 18} 19} 20 21 class Zi extends Fu 22 { 23 int num=8; 24 { 25 System.out.println("constructor code..."+num);//4 26 num=10; 27} 28 Zi() 29 { 30 super(); 31//Display initialization 32//Construction code block initialization 33 System.out.println("Zi constructor..."+num);//5 34} 35 void show() 36 { 37 System.out.println("Zi show..."+num);//3 38} 39} 40 41 class Test 42 { 43 public static void main(String[] args) 44 { 45 new Zi(); 46} 47} Copy code

2017.8.28

Abnormal: It is an abnormal situation that occurs during operation. . . .

In Java, the abnormal situation is described and encapsulated in the form of classes

The class that describes the abnormal situation is called the abnormal class

In the past, the normal process code and the problem handling code were combined. Now the normal process code and the problem handling code are separated to improve readability

In fact, the exception is that java encapsulates the problem into an object through object-oriented thinking

2017.9.3

There are many problems, which means that there are many classes described

Extract the commonalities upwards to form an abnormal system

The final problem (abnormal situation) is divided into two categories

Throwable: Whether it is an error, an exception, or a problem, it should be thrown when the problem occurs, so that the caller can know and deal with it

//The characteristic of this system is that Throwable and all its subclasses are throwable.

What exactly does throwability mean? How to reflect the throwability?

In fact, it is reflected by two keywords.

throws, throw, all classes and objects that can be manipulated by these two keywords have throwability

|--1, generally unhandled: Error

Features: It is a serious problem thrown by jvm

This kind of problem is generally not dealt with specifically, directly modify the program

|--2, can be handled, Exception

Features of the system:

The suffixes of subclasses are all suffixed with the parent class name, which is very readable

2017/9/15

For the corner mark is an integer that does not exist, it can be expressed as the corner mark is out of bounds. For the case of a negative number as a corner mark, prepare to use a negative corner mark anomaly to indicate

Negative number subscripts are not defined in Java, so follow the idea of creating exceptions in Java, object-oriented, and customize the negative subscripts and encapsulate them into objects.

This custom problem description becomes a custom exception

Note: If a class is called an exception class, it must inherit the exception system, because only the subclass called the exception system is qualified to have the throwable type and can be operated by two keywords, throw, throws

Classification of exceptions:

1. Abnormality detected at compile time: As long as Expecetion and its subclasses are in addition to the special subclass RuntimeExpection system

Once such a problem occurs, I hope to detect it at compile time, so that this problem has a corresponding processing method, and such problems can be dealt with in a targeted manner.

2. Exceptions are not monitored during compilation (runtime exceptions): This is the occurrence of RuntimeExpection and its subclasses in Expection. The function cannot be continued and the operation cannot be performed.

More often, it is caused by the caller s reason or caused by the change of internal state, then this kind of problem is generally not dealt with, directly compiled and passed, and at runtime, the program when the caller is called is forced to stop.

Let the caller correct the code

 Therefore, when customizing exceptions, either inherit Expection or RuntimeExpection.

The difference between throws and throw:

1. Throws is used in the function, and throw is used in the function

2. Throws throws an exception class, which can throw multiple, separated by commas, and throw throws an exception object

The capture form of exception handling:

This is a form that can be used to deal with exceptions specifically. The specific format is:

try

{

//The abnormal code that needs to be detected

}

catch()

{

//Code for handling exceptions

}

finally

{

//Code that must be executed

}

Principles of exception handling:

1. If the content of the function throws an exception that needs to be detected, then the function must be declared, otherwise it must be caught in the function with try and catch, otherwise the compilation will fail

2. If the function that declares the exception is called, either try, catch, or throws, otherwise the compilation fails

3. When to use catch and when to use throws?

Function content can be solved, use catch

Can't solve it, use throws to tell the caller, and the caller will solve it

4. If a function throws multiple exceptions, then when calling, there must be corresponding multiple catches for targeted processing

There are a few exceptions that need to be detected inside, just throw a few exceptions, throw a few, just catch a few

1 class Demo 2 { 3 public int show(int index)throws ArrayIndexOutOfBoundsException 4 { 5 if(index<0) 6 throw new ArrayIndexOutOfBoundsException("run bat"); 7 int[] arr=new int[3]; 8 return arr[index]; 9 } 10} 11 class Angel_Kitty 12 { 13 public static void main(String[] args) 14 { 15 Demo d=new Demo(); 16 try//Abnormal code that needs to be detected 17 { 18 int num=d.show(-1); 19 System.out.println("num="+num); 20} 21 catch(ArrayIndexOutOfBoundsException e)//Handle exception code 22 { 23 System.out.println(e.toString()); 24//return;//will not print out the line "over" 25//System.exit(0);//Exit the JVM, it's over here, neither the finally nor the print output "over" line will be executed 26} 27 finally//Code that must be executed 28 { 29 System.out.println("finally"); 30} 31 System.out.println("over"); 32} 33} 34/** 35 Connect to the database 36 Query Expection 37 Close connection 38 */ 39 40/** 41 try catch finally combination features 42 */ 43 44/** 45 1.try catch finally 46 */ 47 48/** 49 2.try catch (multiple) When there is no necessary resource to be released, it is not necessary to define finally 50 */ 51 52/** 53 3. Try finally exception cannot be directly caught, but the resource needs to be closed 54 */ 55 56/** 57 There is no need to declare throws if there is a catch, there is no need to declare throws 58 */ Copy code

2017/9/25

Note for exceptions:
1. When the subclass overrides the parent class method, if the parent class method throws an exception, then the subclass method can only throw the parent class exception or the subclass of the exception.

2. If the parent class throws multiple exceptions, then the child class can only throw a subset of the parent class exceptions.

Simply put: Subclasses overriding the parent class can only throw exceptions or subclasses or subsets of the parent class.

Note: If the method of the parent class does not throw an exception, it must not be thrown when the subclass is overwritten.

2017/10/25

Object-oriented: access between packages

Summary: For access to classes between packages, the classes in the accessed package must be public, and the methods of the classes in the accessed package must also be public

Permissions:

public protected default private

Ok ok ok ok in the same category

Ok ok ok in the same package

Ok ok in subclass

OK in different packages

 

The principle of importing packages: import which class is used

import packa.DemoA;//Imported the DemoA class in the packa package

import packa.*;//Imported all the classes in the packa package

packa\DemoA.class

packa\abc\DemoAbc.class

import packa.abc.*;//Imported all the classes under the sub-package abc in the packa package

Import is to simplify the writing of classes

Jar: the compressed package of java

2017/10/26

Process: A process in progress (literal translation)

Thread: is a control unit (execution path) responsible for program execution in the process

There can be multiple execution paths in a process, called multithreading

There must be at least one thread in a process

Open multiple threads to run multiple parts of code at the same time

Each thread has its own running content, this content can be called the task to be performed by the thread

Multithreading benefits: solve the problem of multiple parts running at the same time

Disadvantages of multithreading: too many threads return to the reduction of efficiency

In fact, the execution of the application is done by the cpu doing fast switching, this switching is random

When the JVM is started, multiple threads have been started, and at least two threads can be analyzed

1. Thread that executes the main function

The task code of this thread is defined in the main function

2. Thread responsible for garbage collection

How to create a thread?

Create thread method one: inherit Thread()

1. Define a class that inherits the Thread class

2. Override the run method in the Thread class

3. Directly create a subclass of Thread to create a thread

4. Call the start method to start the thread and call the task run method of the thread to execute

The name of the thread can be obtained through the getName of Thread, Thread-number (starting from 0)

The name of the main thread is main

The purpose of creating a thread is to open an execution path to run the specified code and other codes to run at the same time

And running the specified code is the task of this execution path

The tasks of the main thread created by jvm are defined in the main function, but where are the tasks of the custom thread?

The Thread class is used to describe threads. Threads need tasks. Therefore, the Thread class also describes tasks. This task is reflected by the run method in the Thread class. In other words, the run method is a function that encapsulates a custom thread to run tasks.

The definition in the run method is the task code to be run by the thread

The thread is started to run the specified code, so only inherit the Thread class, and overwrite the run method, and define the running code in the run method.