Java basics 2

Source: Internet
Author: User

Java basics 2
11. Packaging class (Integer)

A) common methods:
I. Integer. MAX_VALUE (); // get the maximum value of int
Ii. Integer. MIN_VALUE (); // get the minimum value of int
Iii. toBinaryString () // convert to binary
Iv. toHexStrng () // convert to hexadecimal

12. abstract class

A) abstract class features:
I. The abstract method must be in the abstract class;
Ii. abstract methods and abstract classes must be modified by abstract keywords;
Iii. abstract classes cannot use new to create objects, because it is meaningless to call abstract methods;
Iv. To use methods in abstract classes, you must create a subclass object to call all Abstract METHODS After the subclass rewrites them;
V. If the subclass only covers some abstract methods, the subclass is still an abstract class.
B) format: [Access Controller] class name {
Attribute;
Access Controller return type method name (parameter list ){
// Method body; [return value]
}
Access Controller abstract return type method name (parameter list );
}
Example: package B;
Public class AbstractDemo {
Public static void main (String [] args) {Chinese c = new Chinese ();}
}
Abstract class Chinese {
Public abstract void show ();
}
Abstract class D {
Public void show () {System. out. println ("213 ");}
}

13. interface --- the instance object cannot be used, that is, the new interface cannot be used.

A) Definition: When the methods in the abstract class are abstract, the class can be expressed in the form of interfaces.
B) format:
1. Common definitions in Interfaces: constants and abstract methods
2. All the members in the interface have fixed modifiers.
Constant: public static final
Method: public abstract
All the Members in the interface are public.
C) the interface cannot create objects. When the quilt class is implemented, the subclass can be instantiated only when it overwrites the abstract methods in the interface. Otherwise, the subclass is an abstract class.
The interface supports multiple implementations of implements, but the interface cannot implement the interface. It can inherit (multiple inheritance) interfaces.
D) Example
Public class InterfaceDemo {
Public static void main (String [] args) {SubInter si = new SubInter (); System. out. println (si. NUM); System. out. println (SubInter. NUM); System. out. println (Inter. NUM );}
}
Interface Inter {
Public static final int NUM = 3; public abstract void show ();
}
Class SubInter implements Inter {// implementation Interface
Public void show (){}
}

Iv. Singleton Design Model

A) Definition: it is a fixed solution to the same problem. a singleton is to create only one object.
B) To ensure that the object is unique: 1. To prevent other programs from creating too many such objects, first control other programs to create such objects; 2. To make other programs accessible, define the object in this class; 3. Provide access methods for convenient access
C) Use Case: when only one object needs to be created
D) define steps:
1. private Constructor
2. private static Instance Object
3. public static external access method
I. Code implementation:
1. First: Hungry Chinese-Initialize first
Private int;
Private (){};
Private static A a = new ();
Public static get (){
Return;
}
2. Type 2: Lazy-initialization during call-delayed Loading
Private int;
Private (){};
Private static A a = new ();
Public static get (){
If (a = null) {a = new ();
}
Return;
}
E) benefits:
I. control resource usage
Ii. Control the number of instances generated
Iii. enable communication between multiple unrelated two threads or processes

15th, package

A) Definition: Wrap fields and methods and use modifiers to hide external information and expose exposed methods.
B) Java. lang. *; --- Basic Package, imported by default
C) requirements: 1. The package name must be placed in the first line without comments. 2. The package name is usually an inverted domain name. The package name must be in lower case and does not contain keywords. It cannot start with java or javax.
D) Role: 1. Ease of management; encapsulation needs; prevent class name conflicts
E) import the package using the import keyword;
F) Common packages: java. lang. annotation \ java.net \ java. nio \ java. SQL \ java. util \ javax. SQL \
Javax. xml \ javax. swing

16. Inheritance (extends)-the relationship between classes

A) Implementation Method: inheritance and composition)
I. Inheritance implementation methods include: Implementation inheritance and visual inheritance-the Inheritance (generalization) Relationship between classes
1. Implementation Inheritance refers to the ability to use the attributes and methods of the base class without additional encoding;
2. Visual Inheritance refers to the ability of a subwindow (class) to use the appearance of a base window (class) and implement code;
Ii. Combination (aggregation relationship): interface inheritance and pure virtual class inheritance
1. interface inheritance only uses the names of attributes and methods, but the subclass must provide implementation capabilities.
B) initialization sequence: parent class static initialization block-Child class static initialization block-parent class object initialization block-parent class construction method-Child class object initialization block-Child class construction method, for example:
Package;
Public class B extends {
Static {System. out. println ("----- 4 ----");} {System. out. println ("----- 5 ----");} public B () {System. out. println ("----- 6 ----");} public static void main (String [] args) {B B B = new B ();}
}
Class {
Static {System. out. println ("----- 1 ----");} {System. out. println ("----- 2 ----");} public A () {System. out. println ("----- 3 ----");}
}

17. polymorphism (upward transformation)

A) Disadvantages of Polymorphism
I. The new subclass method will be lost after the upward Transformation
Ii. Upward transformation is safe, but downward transformation is insecure.
Iii. Example:
Package;
// Transition upwards ---- print the type to the right
// Disadvantage: The method and attribute added to the subclass are lost.
Public class A extends Super {
Public void f (Super s) {System. out. println (s);} public static void main (String [] args) {// Super a = new A (); //. A @ 82764b -- print the-type variable // System. out. println ();/A a = new A (); a. f (a); // a. A @ 82764b --- upward Transformation/// Super [] s = new Super [] (new A (), new Super (); // System. out. println (. length); Super [] s = new Super [] {new A (), new Super ()}; System. out. println (s. length); Object o = new int [3]; int [] B = (int []) o; System. out. println (B. length); // compilation error, loss of new methods and attributes of subclass}
}
Class Super {}
B) later binding
I. Associating a method call with a method subject is called binding. If it is bound before the program is executed, it is called pre-binding. Except for the static and final methods in java, all other methods are post-binding.
Ii. Overload -- initial binding --- static binding -- compilation stage
Override-later binding-dynamic binding-runtime
For example: Super a = new subclass (); // upward transformation --- overload to the left, override to the right
C) Implementation of Polymorphism
I. override Rewriting: refers to the method by which child classes redefine the parent class.
Ii. overload: multiple functions with the same name are allowed, and the parameter tables of these functions are different (the number of parameters may be different, the parameter types may be different, and the order may be different)
Iii. covariant Rewriting: The subclass method can be more specific than the return type of the parent class method (the return type of the subclass is the return type of the parent class method)
D) The final, static, and private methods do not have polymorphism.
Field (Field member = Field) does not have polymorphism -- they are all pre-bound -- same variable declaration Type Binding
C) Design Principles:
1. Open and closed principle-open to expansion and closed to modification. The key to implementation lies in abstraction.
2. Lee's replacement principle-Surface-to-base class principle-Where any base class can appear, subclass can certainly appear

18. String (Declaration, creation, initialization, operation (equals/=, conversion, search, truncation, splitting, splitting, replacement, connection ))

A) unicode code is used in java. The memory size of a String is related to its attributes. Data Flow in the JVM during String creation and initialization,
B) declare creation Initialization
I. Format: String variable name = initial value;
Ii. String variable name = new String (initial value );
C) operation:
I. comparison (equals and =)
1. equals ratio is content, = ratio is address, and equalsIgnoreCase ()-case-insensitive
2. Example 1: String d = "123 ";
String d1 = new String ("123 ");
System. out. println (d. equals (d1); // true
System. out. println (d = d1); // false
Ii. charAt (int index) -- returns the char value at the specified index
Iii. length () --- return the length of the string
Iv. Conversion
1. toString () -- return itself
2. toLowerCase ()-convert all strings to lowercase letters
3. toUpperCase ()-converts all strings to uppercase
V. Search
1. indexOf (String key) -- index of the first key returned from the previous search
2. indexOf (String key, int formindex) -- returns the index of the first key found from the specified position.
3. lastIndexOf () --- returns the index of the last key.
Vi. screenshot
1. substring (int bindex, int eindex) -- truncates the source String (begin, end) and returns a New String
Vii. Splitting
1. split (String regex) -- splits the source String into several new strings Based on regex
Viii. Replacement
1. replace (char oldchar, char newchar );
Ix. Connection
1. + or concat connection-connect to the new string at the end of the source string and return the New String
2. "a" + "B ";
X. Create an object
1. String str1 = "abc ";
System. out. println (str1 = "abc ");
Steps:
1) Open up a space in the stack to store the reference str1,
2) Open up a space in the String pool and store the String constant "abc ",
3) Reference str1 to the String constant "abc" in the pool ",
4) The address referred to by str1 is the address of the constant "abc", and the output is true.
2. String str2 = new String ("abc ");
System. out. println (str2 = "abc ");
Steps:
1) Open up a space in the stack to store the reference str2,
2) Open up a space in the heap to store a New String object "abc ",
3) Reference str2 to the newly created String object "abc" in the heap ",
4) The object address referred to by str2 is the heap address, while the constant "abc" is in the pool, and the output is false.
3. String str3 = new String ("abc ");
System. out. println (str3 = str2 );
Steps:
1) Open up a space in the stack to store the reference str3,
2) A new space is opened in the heap to store another String object (different from the String object created in str2,
3) Reference str3 to point to the New String object.
4) str3 and str2 point to different String objects in the heap. The address is also different and the output value is false.
4. String str4 = "a" + "B ";
System. out. println (str4 = "AB ");
Steps:
1) Open up a space in the stack to store reference str4,
2) based on the compiler's optimization function to merge known quantities, the pool opens up a space and stores the merged String constant "AB ",
3) Reference str4 to the constant "AB" in the pool ",
4) str4 refers to the constant "AB" in the pool, and the output is true.
5. final String s = "";
String str5 = s + "B ";
System. out. println (str5 = "AB ");
Steps:
Same as 4
6. String s1 = "";
String s2 = "B ";
String str6 = s1 + s2;
System. out. println (str6 = "AB ");
Steps:
1) open an intermediate storage reference s1 in the stack, s1 points to the String constant "a" in the pool ",
2) Open up an intermediate storage reference s2 in the stack. s2 points to the String constant "B" in the pool ",
3) create an intermediate storage reference str5 in the stack,
4) s1 + s2 restores a New String object "AB" through the toString () method in the last step of StringBuilder. Therefore, a space is opened in the heap to store this object,
5) Reference str6 to the New String object restored in the heap (s1 + s2,
6) str6 points to the object in the heap, while the constant "AB" is in the pool, and the output is false.
7. String str7 = "abc". substring (0, 2 );

Steps:
1) Open up a space in the stack to store the reference str7,
2) The substring () method restores a New String object "AB" (different from str6). A space is opened in the heap to store this object,
3) Reference str7 to point to the New String object in the heap,
8. String str8 = "abc". toUpperCase ();
Steps:
1) Open up a space in the stack to store the reference str6,
2) The toUpperCase () method restores a New String object "ABC", and no new space is opened in the pool to store the String constant "ABC ",
3) Reference str8 to point to the New String object in the heap.

19th, this

A) this is a pointer to the current object only;
B) use:
I. If it is used in the constructor, it indicates the object being initialized by the current constructor, for example:
1. Person p = new Person ();
2. public Person (int id ){
This. id = id; // equivalent to p. id = id;
3 .}
Ii. If it is used in a method, it indicates the object that is currently calling this method, for example:
1. public show (int id ){
This. id = id; // equivalent to p. id = id;
2 .}
---- P. show ();

20. Static -- data sharing

A) The Static modifier can be used to modify the member variables and methods of a class. It is loaded only once when the class is loaded.
I. when modifying a member variable, the variable becomes a class variable or static variable and belongs to the class. All objects of the class share the same static variable (long life cycle, established during class loading, saved in the Method Area)
Ii. when modifying a method, this method becomes a class method or a static method. You can directly use the class name. the method name () is called. You can also use the object reference name after the object is created. method () call
Iii. Static methods cannot access non-static methods:
1. A static method is also called a class method. It uses the class name directly during the call. you must create an object before calling a non-static method in the format of Object Name. method Name ();
2. When a static method is called, there may be no instance object, and non-static methods cannot be called.

21. Differences and contacts:

A) break and continue and return
I. Both continue and break can end the current cycle, but after the end of the current cycle, the next cycle continues, and break directly jumps out of the loop.
Ii. break can be used in multiple cycles to jump out of the loop closest to it, or in multiple branch statements swtich to jump out of the loop.
Iii. continue can only be used in loop statements to end the current loop and execute the next loop;
Iv. The statements after continue and break are not executed.
V. return indicates that the method is terminated and data is returned. The return statements in the method body are not executed.
B) class variables (static), instance variables, and local variables
I. Definition: class variables and instance variables are defined outside the class method, and local variables are defined in the method, form parameters, and code block.
Ii. modifier: class variables must be modified using static, instance variables do not need static, class variables and instance variables can not be assigned a value, and local variables must be initialized first
Iii. use: Class variable call format: Class Name. variable name. You must create an instance object before calling an instance variable. variable name); local variables can be used directly
Iv. loading: class variables (in the stack) are loaded at class loading and end at class end; instance variables (in the stack) are loaded at object calling and end at call end; local variables (in the stack) start at method start and end at method end
C) this and super
I. Operation attribute --- this. attribute: indicates to call the attribute in this class. If the attribute in this class does not exist, search for it from the parent class; super. attribute: indicates to call the attribute in the parent class.
Ii. operation Method --- this. method (): Call the methods in this class. If the methods in this class do not exist, search for them from the parent class. super. method (): Call the method in the parent class;
Iii. Call the constructor -- this (); call other constructor methods in this class. super (): Indicates calling the constructor of the parent class.
Iv. Search range --- this first searches for the Child class. If the child class is not searched for by the parent class, super directly queries the parent class without the Child class;
V. Special: this indicates the current object.
D) String, StringBuffer, and StringBuilder
I. String is an immutable object. Every change to the String type is equivalent to generating a new object. StringBuffer is a variable-length Character Sequence and no new object will be generated after modification.
Ii. The essence of StringBuffer is that it has the capacity attribute. The default capacity is 16. When the initialization length is greater than 16, the capacity is twice the initialization length.
Iii. Methods for String operation characters include "+" and concat. Methods for StringBuffer operation characters include insert, append, and delete (start int, endint)
Iv. Initialization format:
1. String st = "234"; String s = new String ();
2. StringBuffer sb = new StringBuffer ();
Both v. StringBuffer and StringBuilder are character sequences of variable length. In multithreading, the former is safe, and the latter is insecure.
E) equals and =
I. For basic type comparison, you can only use = for comparison, but not equals;
Ii. for the packaging type of the basic type, such as Boolean, Character, Byte, Short, Integer, Long, Float, Double, and other reference variables, = is a comparison address, equals compares the content;
Iii. In the String or the class that overrides the equals method: equals is the ratio content, = is the ratio address
Iv. If the equals method is not rewritten in other classes, the equals and = are used in the same way.
F) Reload and rewrite
I. Overloading and rewriting are both forms of multi-State Representation of classes. Overloading is a form of multi-State Representation of classes. Rewriting is the form of multi-State representation that subclasses inherit from parent classes. Both overloading and rewriting are targeted at methods;
Ii. reload requires a list of parameters with the same name (type, number, and order), regardless of the return type, and a list of parameters with the same name (type, number, and order ), same return type (Collaborative-reference data type, which is its subclass or the same, the basic data type is the same), access modifier is greater than or equal to the parent class, the thrown exception must be less than or equal to the parent class (when the thrown exception is RuntimeException, it can be compiled)
Iii. overloading can be used in constructor methods and general methods, and rewriting can only be used in common methods.
G) Integer and int
I. Type: int is the basic data type, and Integer is the reference data type;
Ii. Integer is the int packaging and belongs to the packaging class;
Iii. Default Value: the default value of int is 0, and the default value of Integer is null.
H) class, abstract class, interface
1. abstract classes need abstract modification, while classes do not need
2. abstract classes can contain common methods and abstract methods, but common classes can only contain common methods.
3. abstract classes and common classes can be inherited, but the subclass of the abstract class must override all abstract methods of its parent class.
4. abstract classes cannot be instantiated. normal classes can be instantiated.
5. interfaces are abstract objects. interfaces can only contain abstract methods and constants. interfaces support multi-inheritance and do not contain constructor and initialization blocks.
I) final, finally, and finalize
I. final is used to declare attribute methods and classes. They indicate that attributes are unchangeable, methods cannot be overwritten, and classes cannot be inherited.
Ii. finally is part of the exception handling statement, indicating that it is always executed
Iii. finalize is a method of Object. This method is called when the garbage collector is executed.

22nd, cannot coexist

A) super () and this (): both must be placed in the method's non-Annotated first line.
B) final and abstract: a final and an abstract
C) abstract and private

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.