Packing class :
Since Jdk5, Java has provided automatic boxing and automatic unpacking, which greatly simplifies the conversion between the basic type and its wrapper class object, and of course, the matching of types should be noted in the process of loading.
public class Intandinteger{public static void Main (string[] args) {//auto-boxing Integer intobj = 5;integer INTOBJJ = 5;//auto-unpacking int A = intobj;//wrapper class implements the conversion of a basic variable to a string with the strings str = "123";//Use a static method to convert int b = integer.parseint (str);//Use a constructor to convert int c = new Integer (str); /multiple overloads of the ValueOf () method, converting the base type to string s = string.valueof (b); String boo = String.valueof (false);//basic type or wrapper class Plus "", automatically converted to string type string SS = A + ""; String sss = intobj+ "";//The wrapper class instance can be compared with the base numeric type, with the value of its wrapper integer i = new integer (6); System.out.println (i > 5);//Two wrapper class instances are compared, only two wrapper classes execute the same object, only equal System.out.println (intobj = = INTOBJJ); True, point to 5system.out.println in the constant pool (intobj = = i);//false/* * Look at the next auto-boxing example, look at the source of the Integer, you will see the following code: static final integer[] cache = new Integer[256];static{for (int i=0;i<cache.length;i++) cache[i] = new Integer (i-128); As can be seen from the above code, Integer will automatically box the integers between -128~127 into an integer, stored in an array, so each boxed integer between -128~127 is directly to the array element, Integers outside this range are automatically boxed to create a new integer instance */integer a1 = 2;integer A2 = 2; SYSTEM.OUT.PRINTLN (a1 = = A2); Trueinteger B1 = 128;integer b2 = 128; SyStem.out.println (B1 = = b2); FALSE//JAVA7 provides a static compare method for all wrapper classes, comparing the size of the base type System.out.println (Boolean.compare (False, true)); -1system.out.println (Intobj.equals (a)); True}}
the difference between = = and equals:
= = compares the basic variables of a numeric type (which do not necessarily require the same type), returns True if the value of the variable is equal, = = compares a reference type variable, returns true if only two variables point to the same object, and = = cannot be used to compare two objects with no parent-child relationship on two types; ) is the method of the object, the general subclass to override the method, the purpose is to compare the two reference variables to point to the object's content is the same, of course, the specific conditions of judgment by the programmer's own rules. Some tired have overridden the method, such as the string class, to compare the contents of two strings for the same
Chang is specifically used to manage some of the data that is determined at compile time and saved in the. class file "ABC" with the New string ("abc") (actually creating two string objects), the constant pool guarantees the same string direct quantity with only one
Static:
/* * 1. Static decorated members belong to class members, including class variables, class methods, static initialization blocks, inner classes, and static cannot decorate the constructor * 2. A static variable that shares the same block of memory area * 3 for all instances of the same class. Class method, even if the instance is null, can still access the class method or variable * 4. Class Members (class methods, initialization blocks, inner classes) cannot access instance members (variables, methods, initialization blocks, inner classes), and vice versa can be * 5. Static variables cannot be declared in a method */public class classnumber{private static void Test () {System.out.println ("testing");} public static void Main (string[] args) {Classnumber classnumber = null; =null, first initialize Classnumber.test ();}}
Final:
Final modifier variable
/* 1.final modifier member variable, once the initial value has been obtained, it can no longer be re-assigned, the final decoration class variable, can only be assigned at the time of declaration or one of the static code block; * Final decorated instance variable, can be in declaration, non-static code block, one of the three constructors to assign a value to the variable * The final modified variable must be specified by the programmer to specify the initial value, otherwise the compilation error *//* * 2.final modifier local variable * Final modifies the local variable, either initialized at the time of declaration, or initializes the final decorated parameter once, and initializes the method when it is called, all methods You cannot assign a value to a variable in the * 3.final to modify the basic type of variables, you need to ensure that the value of the variable can not be changed, when the reference type variable is modified, just ensure that the variable point to the address space * does not change, it can be arbitrary to change the object *//* * 4. Can perform the final variable replaced by the macro A final modified variable, whether it is a class variable, an instance variable, or a local variable, can be used as a direct amount, as a macro substitution if the following three conditions are met, and the compile time replaces all occurrences of the variable with the corresponding value * 1> with the final variable modifier * 2> declaration when the initial value is specified * The value of the 3> variable can be determined at compile time. * Note: In addition to assigning a final variable to a direct amount, if the assigned expression is the most basic arithmetic expression or string direct connection operation, * No ordinary variable, call method, Java compiler will also use this variable as "macro variable" */public class Finaltest{public static int h = 0;public static void Main (string[] args) {final String str = "good person"; str = "great man"; Error final int a = 5; System.out.println (a); The variable A does not exist for the program, which is equivalent to executing SYSTEM.OUT.PRINTLN (5)/* Macro variable */FINAL int b = 2; Macro final String str1 = "Linux Programming"; Macro final String str2 = "Linux" + "program Design"; Macro String STR3 = "program Design"; Normal variable StringSTR4 = "Linux" + str3; Use normal variables, not macro System.out.println (str1 = = str2); True System.out.println (str1 = = STR4); False}public void Test (final int a) {//a = 5; cannot be assigned again}}
Final Modification Method:
/* * 1. Subclasses cannot override methods in the parent class that use the final decoration, or compile error * 2. When a method in a parent class uses the private final adornment, the method is only visible in the class, and the subclass cannot inherit the method * So it's perfectly possible to define a method in the subclass that is exactly the same as the return value, the method name, and the parameter. * 3.final Retouching method can only be overridden, but could be overloaded */public class Finalmethodtest{public final void Test () {}private final void test1 () {}}class childtest extends finalmethodtest{//public void Test () {} compilation error public void Test1 () {}//error: public void test (int a) {}; Can
Final Decorated class:
/* * 1. A class that uses the final decoration cannot have subclasses * 2. Immutable class: When an instance of the class is created, the instance variable of that instance is immutable, and 8 wrapper classes and strings are immutable classes * 3. Custom immutable classes Follow the principle of: * 1> use private final decoration The member Variable * 2> provides a constructor with parameters for initializing member variables based on the parameters passed in * 3> only provides a GET method for the variable, I do not need to provide a set method, because the normal method cannot change the final variable * 4> if necessary rewrite equals () and Hashcode () method * Creates an immutable class, the instance of the immutable class is always in the initialized state, and its control becomes simple */public class finalclasstest{private final String detail; Private final String post;public finalclasstest () {this.detail= ""; this.post= "";} Public Finalclasstest (String detail,string post) {this.detail=detail;this.post=post;} Public String Getdetail () {return detail;} Public String Getpost () {return post;} public boolean equals (Object obj) {if (obj = = this) {return true;} if (Obj!=null && obj.getclass () = = Finalclasstest.class) {Finalclasstest object = (finalclasstest) obj;if ( This.getdetail (). Equals (Object.getdetail ()) && this.getpost (). Equals (Object.getpost ())) return true; return false;} public int hashcode () {return This.getdetail (). Hashcode () +this.getpost (). Hashcode () *11;}}
/* * Design immutable class with references to other classes */class name{private string firstname;private string lastname;public name () {}public name (string firs Tname,string lastName) {this.firstname=firstname;this.lastname = LastName;} Public String Getfirstname () {return firstName;} public void Setfirstname (String firstName) {this.firstname = FirstName;} Public String Getlastname () {return lastName;} public void Setlastname (String lastName) {this.lastname = LastName;}} public class Finalclasstest2{private final name name; Because the name object can be changed, this is contrary to the design immutable class's original intent, public FinalClassTest2 (name name) {this.name=new name (Name.getfirstname (), Name.getlastname ()); Use a different reference}public name GetName () {return name;} public static void Main (string[] args) {name name = new name ("Grandchild", "Goku"); FinalClassTest2 f = new FinalClassTest2 (name); Name.setfirstname ("Pig"); System.out.println (F.getname (). Getfirstname ()); Sun will not be changed to achieve the effect of immutable classes}}
Abstract:
Package abstractpack;/* * 1. Rules for abstract class abstract methods * 1> abstract methods are decorated with the abstract keyword, the class containing the abstract method must be an abstract class, abstract class can not contain abstract methods * 2> abstract class cannot be instantiated, You cannot use the New keyword to create an object of an abstract class, even if the abstract class does not contain abstract methods * 3> and ordinary classes, abstract classes can declare member variables, methods, constructors, initialization blocks, inner classes, the constructor of the abstract class is not used to create an instance, but for the subclass call * 4> As long as the class contains an abstract method, including its own defined abstract method, which does not fully implement the abstract method in the parent class or interface, the class must be declared as abstract class * 2.final and abstract can never be used simultaneously * 3.abstract cannot be modified, local variables, constructor * 4. Abstract and static cannot modify a method at the same time, but can also decorate the inner class * 5.abstract method cannot be *//* for private permissions * Template mode: * 1. Abstract the parent class only defines certain methods that need to be used and abstracts the parts that cannot be implemented into abstract methods. To the subclass to achieve * 2. The parent class may contain methods that call other methods, and the called method may require a specific subclass to implement, as shown in the following example: */class father{}abstract class Speedmeter extends father//can inherit generic class {Private double turnrate;public speedmeter () {}public abstract double Getradius ();p ublic void Setturnrate (double turnrate) {this.turnrate = turnrate;} Public double GetSpeed () {return Math.pi*2*getradius () *turnrate; Call an abstract method that requires a subclass implementation}}public class Carspeedmeter extends Speedmeter{public double Getradius () {return 2.0;} public static void Main (string[] args)//Ingress method must be placed in the public decorated Class!!! {Carspeedmeter speed = new Carspeedmeter ();Speed.setturnrate (3.0); System.out.println (Speed.getspeed ());}}
Interface:
Package interfacepack;/* * 1. Because the interface defines a specification, all interfaces cannot contain constructors and initialization blocks. The interface can contain variables (public static final, which is defined as the default value), * Method (public abstract abstract method, static class method, default defaults method, Java8 above to support class method default method, must be implemented by method) , public static inner class (enum, internal interface) * 2. The interface defines a common specification for multiple classes, so all members are decorated with *//* * interfaces and Abstract classes: * Common: 1. Cannot be instantiated * 2. Can contain abstract methods * different points: * Design Purpose: The interface embodies a specification. For the implementation of the interface, the interface specifies what services the implementation must provide to the outside world, and for the caller of the interface, it specifies what services the caller can get and how to get * when using an interface in a program, it is the standard for coupling between multiple modules, and when an interface is used between multiple applications, It is a communication standard between multiple programs, and the interfaces in a system should not change frequently * abstract class embodies a template-style design idea, can be regarded as intermediate products, to prevent the arbitrariness of sub-design * Usage of the difference: * 1> can not provide methods for ordinary methods implementation, can only be an abstract method, the default Methods, class methods, and abstract methods can * 2> cannot define ordinary members, only static constants * 3> cannot contain constructors * 4> cannot contain initialization blocks * 5> A class can implement multiple interfaces, but only one abstract class is inherited * */public interface Interfacetest{int max_mine = 50;//The public static final decoration is used by default, and void out () is initialized when defined;//normal method uses public a by default Bstract modifies the default void print (Object obj)//Defaults method, which must be supplied with the method body, and cannot be decorated with static {System.out.println (obj);} The static void write (Object obj)//class method, which uses the static adornment, must provide the method body, cannot be modified with default, and can be called directly by the interface {SYSTEM.OUT.PRINTLN (2);}}
interface-Oriented programming:
Package interfacepack;/* * Interface-oriented Programming * 1. Simple Engineering Mode: * Assuming that an output device needs to be assembled for the computer class, we let the computer class coupling the output device's parent interface outputs, later regardless of the output device required by the computer * How to change, the code of the computer class does not need to change. The computer class does not need to produce an instance of the output device, but to the factory class to complete the logic of all production output objects is concentrated in Outputfactory, and the class that needs to use the output object only needs to be coupled to the interface. Instead of * with specific implementation class coupling */public class computer{private output output; Public computer (output output) {this.output = output; }//method to invoke output device ...} Define a factory class, production output device class Factory{public output GetOutput () {return new Printer ();//return new Betterprinter ();}} Interface output{//Some of the methods that you need to provide as an output device//...} Class Printer implements output{//implements the abstract method defined in the interface ...} Class Betterprinter implements output{//implements the abstract method defined in the interface ...} /* 2. Command mode: If a method is to complete a function, but the implementation of this function must wait until execution to determine, you can pass the command as a parameter * Assuming an array operation is required *///define the command interface to encapsulate the processing behavior interface command {void process (int[] target);} The class that handles the array can be used to invoke the class's process method when processing an array, dynamically passing the different implementation class objects of the command interface//to implement different types of operations for the array public class processarray{public void Process (int[] Target,command cmd) {cmd.process (target);}
Inner class :
member Inner class
Package innerclasspack;/* * 1. The member inner class is a class member that is similar to a member variable, a member method, an initialization block, and a local inner class and an anonymous inner class that is not a class member * 2. The upper-level program unit of the outer class is a package, so he has only two scopes, one is the package (default) , one is public, and the outer layer of the inner class is an outer class, it has 4 scopes, * within the class (private), package (default), parent-child class (protected), public, * 3. Non-static inner class: * 1> A non-static inner class can directly access a private member of an external class, and within it holds a reference to an external partial object * 2> If an external class wants to invoke instance members (including private) in a non-static inner class, you must first create an object of the inner class, because when an object of the outer class exists, An object of an inner class is not necessarily present, while an object of the inner class must exist * 3> does not allow non-static inner classes to be used directly in static members of external classes, including creating objects, using variables * 4>java does not allow static members to be defined in non-static inner classes, including variables, method, static initialization block * 4. Static INNER class: * The function of the 1>static keyword is to turn members of a class into class-related rather than instance-related, so the static keyword cannot decorate an outer class, but can decorate an inner class * 2> static inner class can contain static members. You can also include non-static members, and static inner classes can only access instance members of external classes, even instance methods of static inner classes, and cannot access instance members of external classes * because static inner classes are related to external class classes, and when objects of static inner classes exist, there must be objects of external classes that are parasitic by it. A class reference that only holds an external class * 3> static internal classes when the external classes are statically members, so all methods of the outer class, the initialization block can use the static inner class to create the object, define the variable. However, there is still no direct access to its internal members, which can be called by the class name or by creating an object of the inner class. The inner class defined in the 4> interface can only be public static *//* * uses inner classes: defining variables, creating instances, inheriting * 1. Outside Internal classes are used inside a class: Not much different from using normal classes, just be careful not to use non-static inner classes in static members of external classes * 2. Use non-static inner classes outside the outer class: * 1> If you want to use an inner class outside the outer class, you cannot use private * Default: Can be accessed by other classes in the same package * ProtecTed: Can be accessed by subclasses of external classes in the same package as the outer class * public: accessed by all classes * 2> creates the format of the inner class object: Outerinstance.new Innerconstructor (), that is, to create an instance of the outer class first, When the constructor of an inner class is called by 3> to create a subclass of the inner class, its subclasses also need to include references to the external partial object, so that the subclass's constructor should pass in a reference to the external class object * 4> the subclass of the inner class can be an outer one, but you need to save a reference to the external partial object * 3. Use static inner class outside class: * 1> Create instance: New Outerclass.innerconstructor (); * 2> declaration Subclass: Class Substaticclass extends staticout.staticin{}, to use the constructor of the parent class, the outer class is like a package space * 3> since the inner class is a member of the outer class, can you define the subclass of the outer class, Rewrite its internal class members?? The answer is no, the class name of the inner class is actually the outer class named namespace * Subclass outside the class, the namespace is changed, the inner class is no longer the same inner class, even if the class name is the same *///access non-static inner class class Out{class in//the same package can access {public in (String name) {System.out.println (name);}}} public class Createinnerinstance{public static void Main (string[] args) {out.in in = new Out (). New in ("Lee");//Create Instance}}class Subclass extends Out.in{public Subclass (out)//subclass contains references to external class objects {Out.super ("Hello");}} Accessing the static internal class classes Class Staticout{static class Staticin{public staticin (String name) {System.out.println (name);}}} public class Createinnerinstance{public static void Main (string[] args) {staticout.staticinin = new Staticout.staticin ("Lee"); Create Instance}}class Substaticclass extends Staticout.staticin{public substaticclass (String name)//constructor with parent class {super (name);}}
Local inner classes and anonymous inner classes:
Package innerclasspack;/* * Local inner class: * 1> because the local inner class cannot be used outside the method, you cannot use the access control and the static modifier * 2> If you need to use a local inner class to define a variable, create an instance, or derive a subclass , you can only generate three. class files after compiling * 3> compilation in a method: Jubuinnerclass.class, Jubuinnerclass$1innerbase.class, * jubuinnerclass$s1ubinneb Ase.class, the number is to distinguish the inner class of the same name in the method * Anonymous inner class: * 1> anonymous inner class is suitable for classes that only need to be used once, an instance of the class is created immediately when an anonymous inner class is created, and the class definition immediately disappears * 2> Syntax format: New implementation interface () | Parent class Constructor (argument) {class Body}, an anonymous inner class must implement an interface or inherit a class, and can only be one. * 3> anonymous inner class cannot be an abstract class, cannot have a constructor, can have initialization block * 4> when an anonymous inner class is created by implementing an interface, it has only one implicit parameterless constructor, so the new keyword cannot pass in the parameter value after it, and if you create an inner class by inheriting the parent class, * It has a constructor similar to the parent class, which is the same as the constructor's formal parameter list. * 5> before JAVA8, Java requires that local variables accessed by local inner classes and anonymous inner classes must be of the final type, and this restriction is canceled after Java8, and if the local variable is accessed by an anonymous inner class, it is automatically added to the final modifier. *///local inner class public classes jubuinnerclass{public static void Main (string[] args) {class innerbase{int A; Public Innerbase () {}}class subinnebase extends Innerbase//method {int B;} Subinnebase sub = new Subinnebase (); SUB.A = 1;sub.b = 2; SYSTEM.OUT.PRINTLN ("Variable value of the subclass a:" +sub.a+ "B:" +sub.b);}} Anonymous inner class interface Product{public double GetPrice ();} public classjubuinnerclass{public void Test (product p) {System.out.println ("Price of Commodity:" +p.getprice ());} public static void Main (string[] args) {Jubuinnerclass j = new Jubuinnerclass (); J.test (new Product ()//Price of commodity: 11.11{public Double GetPrice () {return 11.11;}});}} Call local variable Interface a{void test ();} public class Jubuinnerclass{public static void Main (string[] args) {int = 8; A = new A () {public void Test () {//age = 7; The use of the final variable must be used in accordance with the Rules System.out.println (age);}; A.test (); 8}}
This part is a very important part of the Java Foundation, is also the interviewer's favorite, need to master.
Java-based wrapper classes, static,final,abstract, interfaces, and internal classes