★ master the development steps of java application and java applet in jdk environment
Naming conventions:
Package all lowercase experience.
Class, interface, enumeration type, NeedHelp (Pascal nomenclature) is capitalized at the beginning of each word.
Constants are all capitalized CNT.
Variables, methods, attributes, members, except the first word, each word is capitalized mTeacher (hump naming method).
★ basic sequential structure of java
1 various basic type names (keywords), memory space occupied, default values, etc
2 constants and variables of various basic types: how to define them
3 Java operators
4 type conversion
5 String (definition, comparison, common methods provided by String, etc.)
6 basic input and output (console output and keyboard input)
7 process control
8 one dimensional array
★ objects and classes
OPP achieves three goals of software engineering: reusability, flexibility and expansibility
1 object
Class instances are individual and dynamic
Definition of class 2
The template for creating objects is a data type and static
Construction method of class 3
Modifier (static) (final) class name (extensions) (implements){
Class body (member, variable, attribute, method)
}
Modifier:
public protected default private indicates access rights
-
Public, all classes and packages (cross packages are allowed). Just use imported packages under different packages
-
Protected this package and all subclasses (subclasses can span packages)
-
default, used only in this package
-
Private is only used in this class. Generally, private is used for method construction. I haven't seen it used to build classes
By default, the construction method has only one parameterless construction. When you customize a parameterless construction, the system's own parameterless construction cannot be used unless you customize a parameterless construction
4 this, final, static usage
1.This is a reference to the current object
2. The variable modified by final must be initialized and cannot be modified once initialized
3. Static methods, static variables are modified with static
It belongs to the class level, not the object level. It can be called directly by class name or by object name. All objects of this class can be modified
5 value transfer of method parameter java
All parameter passes are value passes
6 overloading of methods:
The method name in a class is the same, but the number, type or order of parameters are different, which is independent of the return value (overloading has no requirements for the return value, which can be the same or different)
Note: 1 The method name is the same, the parameter type is the same, and only the return value is different. This does not constitute an overload
2. Only the names of formal parameters are different, which does not constitute method overloading.
3. Like ordinary methods, constructors can also be overloaded.
(two methods have the same name, the same parameters and different return types (different method types, but this will not happen, and different types of the same method name will conflict), then this is not a valid method overload example)
Summary; The method name is the same, the method type is the same, and the parameter list is not exactly the same
The same return value is not required
7 object instantiation
Class name object name = new class ();
8 package creation and import keywords
9 properties
getter and setter methods for member variables
★ inheritance
Function: reuse the methods and attributes of classes, and add new methods and attributes on this basis.
Implementation of class 1 inheritance
Modifier class subclass name extends parent class name{
Class body
}
Only one parent class can inherit
Without extensions, Java. Net is inherited by default lang.Object
Subclasses inherit all members and properties of the parent class
2. Super and this keywords
Super explicitly calls the parent class constructor. super. Property or method that explicitly calls the properties and methods of the parent class.
The super statement calling the parent class constructor must be placed on the first line of the subclass constructor, and super can be overloaded.
If the constructor that calls the parent class is not displayed, the default constructor of the parent class will be called by default (parameterless constructor, provided that the parent class has parameterless constructor, user-defined parameterless constructor or system default parameterless constructor).
- The super keyword represents the reference of the parent class space and the reference of this to the current object
- super keyword is to call the constructor of the parent class, and this keyword is to call the constructor of this class
3 method override (override), which is different from method overloading
Method override is to override the method of the parent class in the subclass. Method overload is that there are multiple methods in the same class, and the methods have the same type name and different parameter lists (independent of the return value)
4 polymorphism
Polymorphism is another important feature of object-oriented programming. It means that after the attributes and methods defined in the parent class are inherited by the subclasses, they can have different data types or show different behaviors, which makes the same attribute or method have different meanings in the parent class and its subclasses
Override (method override) and inheritance (subclass objects can be treated as parent types)
Parent class name object name = new child class name ()
instanceof
instanceof is a reserved keyword of Java. On the left is an object, on the right is a class, and the return type is Boolean. Its specific function is to test whether the object on the left is an instance object created by the right class or its subclass. If yes, it returns true, otherwise it returns false.
5 final keyword modifies the usage and meaning of classes and methods
When a class is modified with final, it indicates that the class cannot be inherited. The member variable in the final class can be set to final as needed, and all member methods in the final class will be implicitly specified as final methods.
final modifies a method to indicate that the method cannot be overridden by any derived subclass.
The Final modifier variable is equivalent to defining a constant
Summary: cannot inherit, overwrite or modify
Modifier (static) (final) class name (extensions) (implements)
6 cast type
In Java, due to inheritance and upward transformation, subclasses can be naturally converted to parent classes, but the conversion of parent classes to subclasses requires forced conversion.
Father = new Son() means to construct a Son type object first and then reference it with a father type variable: here, the Son object instance is transformed upward to father, but please note that the essence of this father object instance in memory is still Son type, but the reference type of new Son() is set to father
It is feasible to use weaker types to refer to stronger objects. However, it is not necessarily feasible to refer a type with strong function to an object with weak function. There are some conditions.
Son son = (Son) father;
This statement is feasible. The variable Son refers to the address of the variable father (the mutual reference of the two variables), and the object address referenced by the father is an object of Son type created by new Son(). Here, only the referenced type is forcibly converted to Son, and the object stored in its essential reference address is of Son type, so it is feasible. Therefore, the Son type variable here refers to the father type object, which is feasible through forced type conversion.
7 abstract classes and abstract methods
The reason for the emergence of abstract classes: a behavior of a subclass cannot be determined in the parent class, but the subclass must have a behavior to define abstract methods.
public abstract type method name (); (Abstract cannot be omitted)
Abstract methods have no method body. Abstract methods must be overridden in subclasses.
External class writing:
Internal class writing:
Internal class writing:
(these three classes are written separately)
A class containing abstract methods must be an abstract class.
Abstract classes cannot be instantiated and must be inherited and implemented.
8. Various access control permissions of members
Public protect default private, which says
9. Common methods provided by object: equals(), toString(), hashCode()
Object is the parent of all classes.
equals():
Implementation process: first compare the addresses, return true, and then judge whether the object in parentheses is a string type (string equality has been rewritten). If it is not a string type, return false. If it is a string type, continue to judge the length of the two strings. If the lengths are not equal, return false, If the length is equal, continue to compare each letter in the string. If one letter is different, return false until there is no problem comparing to the last letter, and then return true
Used to compare whether the contents of two objects are equal
For custom types, if you want equals to implement the content, you need to override it
public boolean equals(Object o) { ... }
Different from==
==: if the comparison object is a basic data type, the comparison is whether the values are equal;
If you are comparing the data type of reference (new memory needs to be allocated), you are comparing whether the address values of the object are equal.
toString: returns a string representing the value of an object
public String toString() { return...; }
hashCode: hash code
public int hashCode() { return Objects.hash(...); }
10 generic array listarraylist
Non generic ArrayList arr=new ArrayList(); Any type of object can be put in
Generic ArrayList < Object > arr = new ArrayList < Object > (); Objects have fixed type requirements
Dynamic arrays can only store objects, not values
11 object wrapper
Sometimes, you need to convert a basic type such as int to an object. All primitive types have a corresponding class. For example, the Integer class corresponds to the primitive type int.
In general, these classes are called wrapper s. The names of these classes are obvious: Integer, Long, Float, Double, Short, Byte, Character, Void, and Boolean (the first six classes are derived from the public superclass Number)
The object wrapper class is immutable, that is, once the wrapper is constructed, the value wrapped in it cannot be changed. At the same time, object wrapper classes are still final, so their subclasses cannot be defined.
For example, interger a = 10; 10 cannot be changed. The next instruction is a=11; When, the value of a becomes 11, but only a new object is created. A points to the object with the value of 11 without changing the object with the value of 10.
Automatic packing:
ArrayList list = new ArrayList<>();
list.add(3); Will automatically become a list add(Interger.valueOf(3));
Automatic unpacking:
int n = list.get(i) translates into: int n = list get(i). intValue();
12 enumeration class
Define enumeration class
Modifier enum enum class name{
}
Example 1:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } //The two classes are separate public class Test { public static void main(String[] args) { Day day= Day.MONDAY; System.out.println(day); //MONDAY } }
Example 2:
public enum CurrencyUnit { DOLLAR("dollar"), POUND("pound"), EURO("euro"), RMB("RMB"), YEN("Yen"); //USD, GBP, EUR, RMB, JPY private final String explanation; public CurrencyUnit(String explanation) { this.explanation = explanation; } }
System.out.println(CountryUnit.CHINA.toString()); //name=CHINA, explanation = China, currency=RMB
For comparison of enumeration classes, just use = =
13 reflection mechanism (not considered)
★ interface and internal class
Interface is a special abstract class, which only contains the definitions of constants and methods, without the implementation of methods.
1 Definition and implementation of interface
Define interface: public interface interface interface name {}
Implementation interface: modifier class class name implements interface name {}
Interfaces are abstract and cannot be instantiated
(abstract classes cannot be instantiated, and subclass Inheritance / implementation is required to instantiate in a polymorphic way)
Interfaces are abstractions of behavior.
If you want to instantiate an interface implementation, you can instantiate it by referring to polymorphism: (instantiating an interface through an implementation class is called interface polymorphism)
2 syntax characteristics of interface
Syntax:
- Implement the interface with implements, and the interface can be implemented in multiple ways
- Interfaces can only be inherited from a single
- Interface internal default constant, can only be constant
- The interface cannot have non abstract methods, but can have abstract methods
- Interfaces cannot be instantiated unless they are polymorphic
characteristic:
- You can implement the same behavior of unrelated classes without considering the hierarchy of classes
3 difference between interface and inheritance
- The relationship between classes is inheritance, single inheritance
- The relationship between class and interface is implementation, single implementation and multiple implementation
- Interface and interface are relationship inheritance, single inheritance and multi inheritance
4 definition and use of constant interface (constant bar in interface)
- For constants in the interface, you can omit public static final. Note: this meaning is still expressed without writing. (the default value inside the interface is constant)
- Constants in the interface must be assigned: they must not be assigned.
- The names of constants in the interface are in full uppercase letters separated by underscores. (this naming rule is recommended)
5 difference between interface and abstract class
Same:
- Can't be instantiated
- Both contain abstract methods
Different:
- Interfaces can only have abstract methods and constants, so the definitions in the interface are abstract methods or constants by default
- Constants, variables, construction methods, abstract classes, and non abstract methods can be found in abstract classes (there must be abstract methods)
- Abstract classes include attributes and behaviors, and interfaces are mainly behaviors, which is different from the design concept
6 Lambda expression
Lambda allows functions to be used as arguments to a method
public class Java8Tester { public static void main(String args[]){ Java8Tester tester = new Java8Tester(); // Define function // Type declaration MathOperation addition = (int a, int b) -> a + b; // No type declaration MathOperation subtraction = (a, b) -> a - b; // Return statement in braces MathOperation multiplication = (int a, int b) -> { return a * b; }; // No braces and return statements MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); // No parentheses GreetingService greetService1 = message ->System.out.println("Hello " + message); // Use parentheses GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Runoob"); greetService2.sayMessage("Google"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation){ return mathOperation.operation(a, b); } } //Reprinted from rookie tutorial
7 internal class
The internal class object can access all access permission fields in the external class object. At the same time, the external class object can also access all access permission fields defined in the internal class through the object reference of the internal class
- Ordinary internal class. Ordinary internal class objects depend on external class objects, that is, when creating a ordinary internal class object, you first need to create its external class object
(the test class and Outer class are not in the same piece and are separated)
public class Demo { public static void main(String[] args) { //Create an internal class object and call a method // Inner oi=new Inner(); report errors Outer.Inner oi=new Outer().new Inner(); oi.show(); } }
- The inner class of the member is in the same position as the member variable and member method
- Local inner classes are in the same position as local variables and local methods
- (this is the most commonly used) anonymous inner class is said to be a class, which is essentially an object
public interface Inner { public abstract void show(); } public class Outer { private int num=20; public void method(){ new Inner(){ @Override public void show() { System.out.println("Anonymous Inner Class "); } }; } }
Static decorated static inner classes cannot access members of their outer class objects
8 Comparator and clonable (the latter one is not tested, but I think I can add it to my notes sometime)
Two comparison methods:
1. Internal switch - Comparable interface. Directly compare the implementation of the interface for the class to be compared, and then directly collect sort(arrayList); All right
public abstract class Geometry implements Comparable<Geometry> { /*.Other code, including construction method*/ public int compareTo(Geometry o) {//Override compareTo method of comparator // 1. Return (int) (this. Getsurface-o.getsurface) may lose the decimal point // 2.double t=this.getSurface()-o.getSurface(); // if(t>0) return 1; // else if(t<0) return -1; 0 can only be placed in the last else. If it is placed in the front, - 0 and 0 are inconsistent because of the storage of floating-point numbers // else return 0 //The best way: 3 return Double.compare(this.getSurface(), o.getSurface()); //o means the number in mind, count the book on the right, this means the original number, count the book on the left //The return value is 1, which means that the number on the left is larger than the number on the right, and the left and right numbers are exchanged. //So the numbers on the left are smaller than those on the right, in ascending order } }
2. External comparator. In addition, write a comparison class, and then use the comparison method
private static void sortBySalary(ArrayList staffs) {
Collections.sort(staffs, new SalaryComparator());
}
public class SalaryComparator implements Comparator<Staff>{ @Override //Descending order public int compare(Staff first, Staff second) { return second.getSalary()-first.getSalary(); //The return value is 1, which means that when the number on the right is larger than the number on the left, the left and right numbers are exchanged. //So the numbers on the right are smaller than those on the left, so they are in descending order. } }
**3. Anonymous inner class writing / custom Comparator method**
Collections.sort(array, new Comparator<Staff>() { @Override public int compare(Staff o1, Staff o2) { return o1.getSalary()-o2.getSalary(); } });
4.Lambda writing method
Collections.sort(array,(p,q)->{ //In descending order, the sort function defaults to ascending order return q.getSalary()-p.getSalary(); });
★ graphical user interface design
1 component classification
2. Be able to establish a simple window program
3. How to complete component drawing in window program
4 event processing model several basic ways of event processing
5 common container layout manager, usage
6. Be familiar with the corresponding classes of basic control components and how to use them
★ exception handling
1. Concept of abnormality
Errors encountered during program execution
2 common exceptions in Java
Null pointer exception
Index out of bounds exception
Type conversion exception
Operation condition with exception
3 basic syntax of exceptions
try must be matched with a catch
finally, the code will execute whether there are exceptions or not
When multiple catch es are placed, the parent exception cannot be placed before the child exception
try{
...
}catch(ExceptionType e){
...
}finally{
...
}
The most commonly used is
try{
...
}catch(Exception e){
e.printStackTrace();
}finally{
...
}
4 Classification of anomalies
Both of them are derived from Throwable classes. There are two types: an error (unrecoverable) and an exception (recoverable and treatable)
- Error an internal system error occurred while running
- RunTimeException: run-time exception, which can be passed during compilation. (array out of bounds, null pointer, type conversion)
Both of the above are unchecked exceptions, and the others are checked exceptions
- Non RunTimeException: it must be handled during compilation, otherwise it cannot be compiled.
5 catch exception try... Catch... finally
6 exception declaration throws
throw just throws an exception. That is, the current method cannot handle this exception
An exception that may be thrown when a method is declared in its header
public void method(String name) throws IOException{
}
7 throw exception
throw new Exception();
public static class ScoreException extends Exception{ public ScoreException(String message){ super(message); // Pass exception information } } public static class Teacher { public void checkScore(int score)throws ScoreException { if(score<0||score>100) throw new ScoreException("Score should be 0~100 between"); else System.out.println("Meet score requirements"); } }
★ sets and generics
Collection, Set, List, Map
ArrayList, HashMap, Iterator, ListIterator
Collection, List, Set and Map are all interfaces
1. The implementation class ArrayList corresponding to the list interface
List, sorted by all positions, can have duplicate objects
ArrayList dynamic array
List<Object> arr = new ArrayList<Object>();
2. Implementation class HashMap corresponding to map interface
Each element protects a pair of keys and values without duplicate key objects. Values can be repeated.
HashMap obtains objects through hash algorithm, which has high access efficiency
Map<Type,Type> hm = new HashMap<Type,Type>()
3 Iterator, ListIterator
Iterator iterator is an interface
Use the method iterator() in the collection to obtain the implementation class object of the iterator, and use the iterator interface to receive (polymorphic) the implementation class object of the iterator interface.
hasNext(): judge whether the current pointing element is empty
next(): returns the current pointing element
Iterator<String> iterator=list.iterator(); // [hello, world, java, hello] while(iterator.hasNext()){ String str=iterator.next(); System.out.println(str); } } }
remove
while (iterator.hasNext()){ String str=iterator.next(); if(str.equals("world")) iterator.remove(); }
ListIterator is a unique Iterator of List collection. It inherits from Iterator and also has hasNext() and next() methods
ListIterator has a reverse convenience function
★ stream and file
Finally, remember close
1 InputStream
FileInputStream fis=new FileInputStream("temp.txt");
int read(): reads a single byte of data, and returns - 1 if it reaches the end of the file.
int read(byte[] b); The returned byte size is the actual read byte size. When no element can be read at the end of the read, the returned byte size is - 1
while((len=fis.read(bytes))!=-1){ fos.write(bytes,0,len); }
2 OutputStream
Overwrite write
FileOutputStream fos=new FileOutputStream("D:\\eight_exeperiment\\temp.txt"); // Write a single byte (ASCII code) fos.write(97); fos.write(57); fos.write(55); // a97 // Write one byte array data at a time byte[] bytes={97,57,55}; fos.write(bytes); // Write some data of a byte array at a time fos.write(bytes,1,1); // 9
Final result: a97a979
Append write, and add true after the file name
FileOutputStream fos=new FileOutputStream("D:\\eight_experiment\\temp.txt",true); fos.write("hello".getBytes());
Final result: hello
The two abstract classes Reader and Writer are mainly used to read character streams
3 Reader
Reader is an abstract class, and its subclasses need to be used to create objects (FileReader)
Reader r = new FileReader (file path);
Read method:
The first method: read a single character int read(), read a single character one by one, and the return value is the character itself (ACSII); When read() returns - 1, it proves that the contents of the document have been read
The second method: int read (char [] ARR) reads characters into the array and returns the number of characters read. If it has been read, it returns - 1. The data read from the file is stored in the char array. Generally, the length of the char array is usually defined as 1024
4 Writer
Similar to Reader, Writer is an abstract class, so you can also borrow subclasses to create objects
Writer w = new filewriter (file path);
When writing, i.e. w.write() method, you'd better refresh the stream after using this method, i.e. w.flush(), otherwise the data in the stream will be lost; The close() method of the flow closing operation will execute the flush () method once before the flow closing operation.
The array used for byte stream FileInputStream is bytes, and the char type used for character stream Reader
Reader and Writer learn from the original link: https://blog.csdn.net/weixin_42386014/article/details/81543567
★ multithreading
1 thread concept
Process: is a running program
Thread: it is a single sequential control flow in a process and an execution path
2 two ways to implement threads
1. The custom class inherits the Thread class and overrides the run method
- Define a class MyThread to inherit the Thread class
- Override the run method in the MyThread class
(why rewrite the run method? Because run is used to encapsulate the code executed by the thread, and there is more than the code executed by the thread in the custom thread) - Create an object of the MyThread class
- Start thread
public class MyThread extends Thread{ @Override public void run() { /*...*/ } }
Start thread
MyThread myThread = new MyThread(); myThread.start();
2. Implement Runnable interface (mainly the second one)
- Define a class MyRunnable to implement the Runnable interface
- Override the run() method in the MyRunnable class
- Create an object of the MyRunnable class
- Create an object of Thread class and take the MyRunnable object as the parameter of the construction method
- Thread start
Thread receiveThread=new Thread(new ReceiveMailRunnable());
public class ReceiveMailRunnable implements Runnable{ @Override public void run() { /*...*/ } }
Several important methods of thread
- start()
- The implementation principle of the join() method is to constantly check whether the join thread is alive. If the join thread is alive, let the non join thread wait forever. Until all join threads are completed, other methods of the thread will be called. (all join threads run simultaneously)
try { // Call the join() method of multiple sub threads, and let the main thread wait for them to execute, and then let the main thread execute receiveThread1.join(); receiveThread2.join(); receiveThread3.join(); sendThread1.join(); sendThread2.join(); sendThread3.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("foxmail End of task"); //So the last println is executed when the thread ends
- void setName(String name) returns the name of this thread
- static void sleep(long millis) stops (pauses) the currently executing thread for a specified number of milliseconds
4 synchronization code block synchronized keyword, wait() and notify()
When a thread synchronizes the code block execution area, only if it is still in the area, other threads cannot enter the area
public class SumWorker implements Runnable{ private static Object obj=new Object(); private static long sum=0; private long beg,end; @Override public void run() { for (long i = beg; i <= end; i++) { synchronized (obj) {//Expressed as a static parameter, there is only one lock sum += i; } } } }
wait()
notify()
Wait is because the current code cannot be executed temporarily (if the condition is not met, call wait). At this time, the thread enters the rest state and cannot participate in the contention of cpu time slice. Other threads can compete.
Only when this object calls notify() or other thread objects call notifyAll() can the code participating in the snatch attempt be reproduced.
public void takeChopsticks() { //When taking chopsticks, as long as one chopstick has been occupied, you should give up taking chopsticks and release the lock to enter the wait ing state //After notify is notified, it enters the ready state and re competes for the lock //Calling the wait() method of an object can block the current thread, and the current thread must have the monitor (i.e. lock, or process) of the object if (noChopsticks[pos]||noChopsticks[((pos - 1) + 5) % 5]) { synchronized (obj) { try { obj.wait(); //I have only one chopstick and can't eat. Wait. Don't move the thread first. Release the lock to let other threads compete } catch (InterruptedException e) { e.printStackTrace(); } } // noChopsticks[pos]=true; noChopsticks[((pos - 1) + 5)%5]=true; } } //When putting down the chopsticks, release the lock and notify all waiting threads that they can try to grab the time slice of the cpu //notify() and notifyAll() wake up the waiting thread on the current object; Notify () wakes up a single thread, while notifyAll () wakes up all threads. public void putDownChopsticks(int i) { synchronized(obj) { noChopsticks[pos]=false; noChopsticks[((pos - 1) + 5)%5]=false; System.out.println("Activity"+i+": The philosopher-" + Thread.currentThread().getName() + " has finished eaten"); obj.notifyAll(); //After the lock is released, other threads can continue to compete, and other threads will make if judgment again } } }