编程知识 cdmana.com

Introduction of java basic knowledge

One 、 Basic knowledge of :
1、JVM、JRE and JDK The difference between :
    JVM(Java Virtual Machine):java virtual machine , Used to guarantee java The cross platform features of .
                  java Language is cross platform ,jvm It's not cross platform .
    JRE(Java Runtime Environment):java Operating environment , Include jvm+java Core class library of .    
    JDK(Java Development Kit):java Development tools , Include jre+ development tool

2、 environment variable path and classpath What is the role of ?
C:\Program Files (x86)\Java\jre7\bin;C:\Program Files (x86)\Java\jdk1.7.0_72\bin
    (1)path It's configuration Windows Search path for executable , The extension is .exe The directory where the program files are located ,
        Is used to specify the DOS The path of the window command .
    (2)Classpath It's configuration class Directory of files , Used to specify the class search path ,JVM It is through it to find this kind of class Class file .    
    
3、 What's the use of variables ? Why define variables ? When to use ?
     answer : Role of variables : Used to store data .
         Why define variables : Used to keep the same type of constant , And can be reused

4、& and && The difference between ?
     answer :(1)&& There will be a short circuit , If we can judge the result of the whole expression through the first expression , Then do not continue the operation of the following expression ;
          You can only operate boolean Type data ;
        (2)& There will be no short circuit , Operate the entire expression . It can be operated boolean Data can also be manipulated .

5、 Identifier naming rules :
     By digital (0-9), Case letters , as well as _ and $ form .
     Cannot start with a number .
     You can't use keywords to define names .

6、 data type :
    (1) Basic data type (4 class 8 Kind of ):
         Integer types :byte、short、int、long
         Floating point type :float、double
         Character type :char
         Boolean type :boolean(ture false)
    (2) Reference data type :
         class
         Interface
         Array

7、 Type conversion
     Precision from high to low  double  float  long  int  short(char)  byte 
    (1) Automatic type conversion   Will be a low precision --- High precision  
    (2) Cast   Will be a high precision --- Low precision ( The accuracy will drop )

8、java Three technical structures of language
    J2EE: Enterprise Edition
     It's a set of solutions for developing applications in an enterprise environment .
     The technologies included in the technical system are as follows Servlet、Jsp etc. , Mainly for Web Application development .
    J2SE: The standard version
     It's a solution for developing common desktop and business applications .
     The technology system is the foundation of the other two , Can complete the development of some desktop applications .
     such as Java Version of mine sweeping .
    J2ME: Small version
     Is for the development of consumer electronics and embedded devices to provide solutions .
     The technology system is mainly applied to small-scale electronic consumer products , Such as applications in mobile phones .

9、java Cross platform :
     adopt Java Applications written in language can run on different system platforms .
     Cross platform reasons :
     As long as it needs to run java On the application's operating system , Install one first Java virtual machine (JVM Java Virtual Machine) that will do .
     from JVM To be responsible for Java The operation of the program in the system .

10、 The representation of signed data ( The second point is )
     Original code , Inverse code ( Reverse the original code ), Complement code ( Inverse code +1).

11、 function
     Definition : Function is defined in the class with a specific function of a separate small program .        
     characteristic :
         Defining function can encapsulate function code
         It is easy to reuse this function
         Functions are only executed if they are called
         The emergence of functions improves the reusability of code
         For functions with no specific return value , Return value type with keyword void Express ,
         In this function return If the statement can be omitted in the last line .
     Two definiteness of the application of function :
         Be clear about the final result of the function to be defined ?
         Clearly in the process of defining this function , Whether unknown content is needed to participate in the operation

12、 heavy load :
     Concept : In the same class , More than one function with the same name is allowed , As long as they have different number or type of parameters .    
     characteristic : Independent of return value type , Just look at the parameter list ( Parameter type and number of parameters ).    
     benefits : Easy to read , Optimized programming .    
    
13、 Array :
     Concept : A collection of the same data type .    
     benefits : Can automatically give elements in an array from 0 Numbered starting , Easy to operate these elements .14、 Memory structure :
     Stack memory : Used to store local variables , When the data is used , The occupied space will be released automatically .
     Heap memory : Arrays and objects , adopt new All instances created are stored in heap memory .
     Method area : Static members 、 Constructors 、 Constant pool 、 Thread pool
     Local method area :window The system occupies

If you are learning now Java, At the beginning of learning Java There is no systematic learning course in the process , You can add QQ Group 685168267 Collect the learning materials , Interview questions , Development tools, etc , There are senior people in the group java The teacher answers questions , Every day, there will also be live lectures on the basic part and architecture , As long as I really want to learn Java People welcome .

     Two 、 object-oriented
1、 Object oriented idea :
    (1) summary : Object oriented is relative to process oriented , Process oriented emphasizes function , Object oriented emphasizes the encapsulation of functions into objects ,
          Emphasis on functional objects ;
    (2) Ideological characteristics :
         A: It's a kind of thought in line with people's thinking habits ;
         B: Simplify complicated things ;
         C: Turn programmers from executors to commanders ;

          For example, I want to achieve some results , I'm looking for someone who can help me achieve this result , I'll buy a washing machine if I want to wash ,
          As for how to wash, I don't care .
    (3) features :
         encapsulation : Hide object properties and implementation details , Only public access is provided
         Inherit : When the same properties and behaviors exist in multiple classes , Extract these into a single class , So many classes don't need to be defined
               These attributes and behaviors , Just inherit that class .
         polymorphic : The various states represented by an object at different runtime of a program , A reference to a parent or interface points to a subclass object
2、 Classes and objects :
     class : A description of something in the real world , It is abstract. , A conceptual definition .
     object : The individual in which things exist .

3: The difference between member variable and local variable ( a key )
    (1) Scope
         Member variables : Works for the entire class .
         local variable : Valid only in a certain range .( Generally speaking, it means the method , Inside the sentence )
    (2) Storage location
         Member variables : Exists with the creation of objects , Disappear with the disappearance of the object , Stored in heap memory .
         local variable : When a method is called , Or the statement exists when it is executed , Stored in stack memory .
               When the method call is finished , Or at the end of the statement , Just release it automatically .
    (3) Initial value
         Member variables : There are default initializers .
         local variable : There is no default initializer , It must be assigned before use .

4、 Anonymous object
    (1) An anonymous object is an object without a name . It's a shorthand form of an object .
    (2) Application scenarios
        A: Call methods in the class only once .
        B: It can be used as an actual parameter in method passing

5、 encapsulation :
     Hide the properties and implementation details of the object , Only public access is provided ; For example, computer case 、 Notebook, etc
     benefits :
         Isolate change ;
         Easy to use ;
         Improve reusability ;
         Improve safety

6、 keyword private: The embodiment of encapsulation in the code
    (1) Private , Permission modifier
    (2) Used to modify member variables and member functions
    (3) use private Decorated members are only valid in this class
    (4) Private ownership is an embodiment of encapsulation

7、 Construction method :
    (1) characteristic :
         The method name is the same as the class name
         No return type
         no return value
    (2) effect : Constructors are used to create objects , And initialize it , As soon as the object is created, the corresponding constructor will be called automatically ,
    (3) Precautions for construction method :
        A: If a custom class has no constructor , The system will default to a nonparametric construction method .
        B: If a custom class provides a constructor , that , The system will no longer give the method of nonparametric construction .
           This is the time , You don't have to use parameterless construction .
           If you want to use , that , It is necessary to give the method of nonparametric construction by hand .

         Suggest : In general , Our custom classes all need to manually give nonparametric construction methods .
    (4) The difference between construction method and member method
        A: Format difference
             The construction method is the same as the class name , And there is no return type , There is no return value .
             Common member methods can be named as you wish , There must be a return type , Can have no return value .
        B: The difference in function
             Construction methods are used to create objects , And initialize the value .
             Common member methods are used to accomplish specific functions .
        C: Call difference
             The constructor is called when the object is created , An object is created , Call the corresponding constructor only once
             The normal member method is called by the created object , It can be called multiple times

8、 Building blocks of code :
    (1) effect : Initialize the object , As soon as the object is created, it will execute , And it takes precedence over constructor execution
    (2) The difference between building blocks and constructors :
         Building code blocks is to initialize the commonness of all different objects
         The constructor initializes the corresponding object

9、this keyword
    (1)this Keyword represents a reference to an object of this class , Who is calling this The way it works ,this On behalf of whom  
    (2)this Usage scenarios of
        A: Used to distinguish member variables with the same name from local variables ;
        B: When you define a function , When the object calling the function is used inside the function , Because at this time, the object has not been established , so this Represents this object
        B: Call between constructors
            ** This is the time ,this( Parameters ) Must exist as the first statement .

10、Person p = new Person(); What has been done in memory .
    (1) take Person.class The file is loaded into memory .
    (2) If p Defined in the main method , that , It will open up a variable space in the stack space p.
    (3) Allocate space for objects in heap memory .
    (4) Initialize the members of the object by default .
    (5) Initialize the display of the members in the object .
    (6) Call the building block to initialize the object .( If not, don't execute )
    (7) Call the constructor to initialize the object . Object initialization complete .
    (8) Assign the memory address of the object to p Variable , Give Way p The variable points to the object .

11、static keyword :
    (1) Static means , Used to modify member variables and member functions
    (2) Static characteristics :
         Load as class loads
         Prior to the existence of objects
         Share... With all objects
         Can be called directly by class name
    (3) Static considerations
        A: Static methods can only access static members
             Why? : Because the static content is loaded as the class loads , It's advanced memory .
        B: Cannot use... In static methods this,super keyword
        C: The main method is static
            public static void main(String[] args)
            public: Public means , Is the maximum permission modifier .
            static: because jvm call main Method time , No objects created .
                    Can only be called by class name . therefore ,main Must use static modification .
            void: because main The way is to be jvm call , You don't need to return a value . use void modification .
            main:main Is the main meaning , therefore jvm Adopted the name . It's the entrance to the program .

            String[]: Array of strings
            args: Array name

             During operation , adopt java Order to args Array assignment .
             Format :java MainTest hello world itcast
    (4) The difference between static variables and member variables
        A: Call mode
             Static variables are also called class variables , Can be called directly through the class name . You can also call... By object name .
             This variable belongs to the class .
             Member variables are also called instance variables , Can only be called by object name . This variable belongs to the object .
        B: Storage location
             Static variables are stored in the static area of the method area length .
             Member variables are stored in heap memory .
        C: Life cycle
             Static variables exist as classes load , Disappear with the class . Long life cycle .
             Member variables exist as objects are created , Disappear with the disappearance of the object .
        D: Relevance to the object
             Static variables are data shared by all objects .
             Member variables are data specific to each object .
    (5) The advantages and disadvantages of static
         advantage :
         Store the shared data of the object in separate space , Save memory , There is no need to store a copy of each object
         Can be called directly by class name
         disadvantages :
         The life cycle is too long , Disappear with the class
         Access appears permissions , That is, although static is good, it can only access static
    (6) What uses static ?
        A: When all objects share some data , Define this member variable as statically decorated .
        B: When a method does not access a non static member of the class , You can define this method as static decoration .

         The static life cycle is longer , So it is not recommended to use .
    (7) Static code block
        A: It only executes once , It is better than main First of all .
        B: Execution order
             Static code block -- Building blocks of code -- Construction method

12、 Make API( The second point is )
    API( full pinyin ):Application Program Interface Application programming interface .
    (1) The contents of the class need to be annotated with documentation .
    (2) Use JDK\bin In the catalog javadoc Tools .
         Format :javadoc -d Catalog -author -version ArrayTool.java
 
13、 Singleton design pattern :
    (1) Design patterns :
         An effective way to solve a problem , It's an idea , It's a summary of the law
    (2) To ensure that a class has only one object in memory
    (3) Ideas and steps to ensure uniqueness
        ** To avoid other programs building such objects , First, forbid other programs to create such objects , About to privatize the constructor
        ** For other programs to access such objects , A private object of this class must be created in this class
        ** For the convenience of other programs to access such objects , It can provide a public access way

     such as API Medium Runtime Class is a singleton design pattern .

    (4) Two ways of singleton design pattern
        A: Hungry Chinese style When the class loads , Just create the object .    
        class Student
        {
            private Student(){}
            
            private static final Student s = new Student();
            
            public static Student getInstance()
            {
                return s;
            }
        }
        B: Slacker type When used , To create objects .
        class Student
        {
            private Student(){}

            private static final Student s = null;
            
            public static Student getInstance()
            {
                if(s==null) 
                {
                    // Threads 1 Just came in , Threads 2 Just came in .
                    s = new Student();
                }
                return s;
            }
        }
     The difference between the hungry and the lazy :
        **
         Hungry Chinese is a class that creates an object as soon as it is loaded into memory ;
         Lazy is when classes are loaded into memory , The object doesn't exist yet , Only called getInstance() When the method is used ,
         Object is created .
        **
         Lazy is lazy loading , If multiple threads operate in lazy mode at the same time, there may be thread safety problems , Solving thread safety problems
         It can be solved by adding synchronization . But with synchronization , Compare locks every time , The efficiency becomes slower ,
         So we can add double judgment to improve the efficiency of the program .
         notes : The development is often in the form of starving Han , Because it's simple and safe . Lazy multithreading is prone to problems

14、Math The use of the class ( a key )
    (1) Mathematics operation class : This class does not have a constructor , Methods are static     
    (2) Master the content
        A: Member variables
            **E: Closer than any other value e( That is, the base of natural logarithm ) Of double value .
            **PI: Closer than any other value pi( That is, the ratio of the circumference of a circle to its diameter ) Of double value .
        B: Member method
            **static double abs(double a) 
                 return double The absolute value of value . Return the absolute value
            **static double ceil(double a) 
                 Return to the smallest ( It's closest to negative infinity )double value , The value is greater than or equal to the parameter , It's going to be equal to some integer . 
            **static double floor(double a) 
                 Return to the biggest ( It's closest to positive infinity )double value , The value is less than or equal to the parameter , It's going to be equal to some integer . 
            **max: Returns the larger of the two values
            **min: Returns the smaller of the two values
            **static long round(double a) Returns the closest parameter long.
              static int round(float a) Returns the closest parameter int. 
            **static double random() 
                 Go back to the plus sign double value , The value is greater than or equal to 0.0 And less than 1.0. 
            **static double pow(double a, double b) 
                 Returns the value of the second power of the first parameter . 
            **static double sqrt(double a) 
                  Returns the correctly rounded double The positive square root of the value . 
15、Random The use of the class ( a key )
    (1) A class that produces random numbers
    (2) Master the content
        A: Construction method
            **Random() Create a new random number generator . 
            **Random(long seed) Using a single long Seed creates a new random number generator .
        B: Member method
            **int nextInt() Returns the next pseudo-random number , It is evenly distributed in the sequence of the random number generator int value . 
            **int nextInt(int n) Returns a pseudo-random number , It is taken from the random number generator sequence 、
             stay 0( Include ) And the specified value ( barring ) Evenly distributed between int value .
16、Scanner The use of the class
    (1) You can get the input data from the keyboard
    (2) Master the content
         Construction method :
            Scanner(InputStream source) Construct a new Scanner, The value it generates is scanned from the specified input stream .
             Such as :Scanner sc = new Scanner(System.in);
         Method summary
            sc.nextInt(); Get integer data
            sc.nextLine(); Get string data
17、 Inherit ( a key )
    (1) Extract the same features and behaviors of many classes , Use a class to describe . Let multiple classes have a relationship with this class .
        In this case , Multiple classes can omit a lot of code . This relationship is inheritance .java of use extends Keyword representation .
    (2) Inherited Architecture
        A: Multiple specific objects , Constantly extract shared content up , Eventually a system was formed . This system is called the inheritance system .
        B: The principles of learning and using the inheritance system
            ** Learn what's at the top . Because it is the common content of the whole system .
            ** Create a subclass to use . That is, using the underlying concrete objects .
    (3) The characteristics of inheritance :
        A:java Only single inheritance is allowed in , No more inheritance .
        B:java It can be multiple ( layer ) Inherit .
    (4) Benefits of inheritance :
         The emergence of inheritance improves the reusability of code .
         The emergence of inheritance creates a relationship between classes , It provides the premise of polymorphism .
    (5) Membership in a child parent class
        A: Member variables
             When using a variable in a subclass method :
             First , Find this variable in the local variable of the method , If there is one, use .
             otherwise , Find member variables in this class , If there is one, use .
             otherwise , Find member variables in the parent class , If there is one, use .
             otherwise , Report errors .
        B: Member method
             When using a method with a subclass object .
             First , Find this method in the subclass , If there is one, use .
             otherwise , Find this method in the parent class , If there is one, use .
             otherwise , Report errors .

         The difference between rewriting and overloading ?
             heavy load : In the same category . Same method name , Different parameter list . Overloading can change the return type .
             rewrite : In different classes ( In the child parent class ).
                   The method declaration is the same ( Return type , Method name , The parameter list is the same ).
         Rewriting requires attention to :
            ** The access permission of the subclass method should be greater than or equal to that of the parent method .
            ** Static can only override static . But it doesn't happen .

         Construction method
            ** Instantiation process of subclass
                *** When a subclass creates an object , Will first create the object of the parent class .
                     The default is to call the nonparametric constructor of the parent class .
                *** Subclass construction method , The first line defaults to super()
                *** Why does the first line in the subclass default to super()
                     Because it inherits the use of the members of the parent class , These members must be initialized... Before use ,
                     And they're members of the parent class , therefore , Must be initialized by parent class .
                     therefore , Will create a parent class object first .
            ** When the parent class does not have a parameterless constructor
                 You have to use this perhaps super Call other construction methods .
    (6)this and super The difference between
        this: References representing objects of this class .
        super: Represents the storage space of the parent class .
18、final keyword ( a key )
    (1) The final meaning , Can be used to decorate a class , Method , Variable .
    (2)final Modified classes cannot be inherited .
       final Methods that modify cannot be overridden .
       final The variable decorated is a constant . Can only be assigned once .
        The inner class can only access the final Modified local variables .
19、 abstract class ( a key )
    (1) Multiple classes have the same method declaration , But the methods are different . This is the time , Let's consider extracting method declarations .
        After subclasses inherit , Realize the method body by yourself . There is no method body method , We need to use the abstract logo .
        The abstract keyword is :abstract.
    (2) abstract class :
         This method is called abstract method , The class containing the abstract method is the abstract class .
    (3) Characteristics of abstract classes :
        A: Abstract classes and abstract methods all use abstract To embellish
        B: Abstract class cannot be instantiated
        C: There is not necessarily an abstract method in an abstract class , however , A class with abstract methods must be an abstract class .
    (4) Characteristics of data in abstract classes
        A: Member variables
             There can be variables in an abstract class , You can also have constants .
        B: Member method
             There can be abstract methods in an abstract class , There can also be non abstract methods .
        C: Construction method
             An abstract class is a class , therefore , It has construction methods .
             Although not instantiated by itself . But you can instantiate a subclass .
    (5) Problems in abstract classes
        A: Is there a constructor in an abstract class ? Can it be instantiated ? If not , Why is there a construction method ?
           Abstract classes have construction methods .
               Abstract class cannot be instantiated .
           The constructor in the abstract class is used for subclass instantiation .
        B: Abstract keywords abstract Which keywords can't coexist with ?
          **private:
             Private content subclass cannot inherit , therefore , Can not rewrite .
             however abstract The method of decoration , The request is rewritten . The two conflict .
              **final
            final Methods that modify cannot be overridden .
             and abstract The method of decoration , The request is rewritten . The two conflict .            
          **static
             If an abstract method can pass through static modification , So this method , It can be called directly through the class name .
             Abstract methods have no method body , Such a call makes no sense . therefore , Out-of-service static modification .
        C: Can there be no abstract methods in an abstract class ? If possible , What's the use of such a class ?
           Abstract classes can have no abstract methods .
           There is no abstract method in an abstract class , Just to prevent other classes from creating the abstract class object . This is in awt There are in .
20、 Interface interface
    (1) When methods in a class are abstract ,java Another representation is provided , It's called interface .
        use interface Keyword representation . Class and interface relationship implements Express .
    (2) Member characteristics of the interface
        A: Member variables
             Is a constant , Default decoration public static final    
        B: Member method
             It's all abstract , Default decoration public abstract    
    (3) Relationship
        A: The relationship between class and class
             It's inheritance . Classes and classes can only be inherited by themselves , Multiple inheritance is possible .
        B: The relationship between class and interface
             It's about realizing relationships . Class can implement multiple interfaces .
             Class inherits a class at the same time , Multiple interfaces can be implemented .
        C: The relationship between interface and interface
             It's inheritance . Interfaces can inherit multiple interfaces .
    (4) Interface features
        A: It's the rules of exposure
        B: It's an extension of function
        C: The emergence of interfaces reduces coupling .
             coupling ( The relationship between classes )
             cohesion ( The ability of a class to complete a function )
             Programming specification : Low coupling , High cohesion .
        D: Interfaces can be implemented more . Such as :CPU And motherboard 、 Notebook USB jack 、 Socket
    (5) The difference between interface and abstract class
        A: Abstract classes can only be inherited by a single
            Interfaces can be implemented more , The interface avoids the limitation of multi inheritance .
        B: Data characteristics in abstract classes :
                 Member variables : It could be a variable , It can also be a constant
                 Member method : It can be an abstract method , It can also be a non abstract method
                 Construction method : There's a way to structure
            Data characteristics in the interface :
                 Member variables : Is a constant . Default decoration public static final
                 Member method : It's all abstract methods . There are default embellishments public abstract
                 Construction method : There is no way to construct
        C: Abstract classes define the common functions in the inheritance system .
            The interface defines the extension function in the inheritance system .
        D: Abstract classes are inherited as "is a" Relationship :xx yes yy A kind of
            The interface is implemented as "like a" Relationship :xx image yy A kind of
21、 polymorphic :
    (1) Same object , A variety of running states at different times of a program . give an example : animal , Dogs are dogs , Dogs are animals . water ( Gaseous state , liquid state , solid state )
    (2) Polymorphic premise
        A: There is an inheritance or implementation relationship
        B: Rewriting with methods
        C: Parent class ( Interface ) References point to subclasses ( Realization ) object
    (3) The advantages and disadvantages of polymorphism :
         benefits : Polymorphism improves the scalability and maintainability of the program
         disadvantages : Although it can be used in advance , But you can only access the functions already in the parent class , What runs is the functional content of the later subclass .
               You can't use the specific functions defined in the subclass in advance .
    (4) The characteristics of object calling members in polymorphism
        Fu f = new Zi();
        
        A: Member variables
             Compile to the left , Run to the left
        B: Member method  
             Compile to the left , Run to the right
        C: Static methods
             Compile to the left , Run to the left
    (5) A polymorphic mind
         Command the same group of people to do things . give an example : Lead the army to war , After class .
22、instanceof keyword
        A: Used to determine whether an object is of a certain type .
        B: Format
             Object name instanceof Subclass ( Realization ) name
23、Object class :
    (1) Is the root class of all classes , Superclass .
       java The classes provided in and our custom classes are directly or indirectly inherited from Object class .
    (2)Object Methods in class
        A:void finalize() 
           When the garbage collector determines that there are no more references to the object , This method is called by the object's garbage collector .
        B:Class getClass()
           Get the description class of the bytecode file of the object , I'll talk about reflection later .
          String name = s.getClass().getName();
        C:int hashCode()
           Get the hash value of the object . In fact, it is the decimal representation of the memory address value of the object
        D:String toString()
           Returns the string representation of the object .
           Representation format :
          getClass().getName()+"@"+Integer.toHexString(hashCode());

           Usually when we output the object name , In fact, the underlying call is the object's toString() Method .
           There is no point in this return , therefore , We will rewrite this method , Display the member variable information of the class .
        E:boolean equals(Object obj)
           Used to compare whether the address values of two objects are the same .
           After we get the object , It doesn't make much sense to compare its address value . So this method will also be rewritten .
           Rewrite what to do , It's based on demand .
    (3)== and equals Usage of :
        A:== How to use it? ?
            ** Can be used to compare basic data types , The comparison is whether the values of the basic data types are equal .
            ** Can be used to compare reference data types , The comparison is whether the address value of the object is equal .
        B:equals How to use it? ?
            equals Can only be used to compare the .
            **Object Provided equals Is used to compare whether the object address value is the same .
            ** In the custom class , If I rewrite it equals Method , Then compare according to your own needs .

24、package keyword
    (1) package : It's actually a folder . Used to distinguish the same class name under different packages .
    (2) benefits :
        A: Classify and manage the documents .
        B: Provides multiple namespaces for classes
            aaa.Demo
            bbb.Demo
        C: Write in the first line of the program file .
        D: A package is also a form of encapsulation .
25、import keyword
    (1) Import package keywords
    (2) Format :
        import Package name ;
    (3) Be careful :
        A: There is only one... In a program file package, There can be multiple import.
        B: To guide the classes in the package , Do not import packages from packages .
        C: It usually says import  mypack.Demo, Identify the classes you use .  
    (4) The order of keywords
         class , package , The key sequence of the guide package .
         package -- >   To bag -- > class
26、 What can different modifiers modify
             In this category      In the same bag In subclasses in different packages In different bags
    private        OK    
     Default         OK    Ok        
    protected    OK    Ok        OK
    public        OK    Ok        OK            Ok

             class      Construction method      Member variables      Member method         
    private            OK        OK        OK
     Default         Ok    Ok        Ok        OK
    protected        OK        OK        Ok
    public          Ok    Ok        OK        OK
    static                    OK        Ok
    final        Ok            OK        OK
    abstract    Ok                    OK

     General format :
         Member variables :
         Permission modifier +static/final+ data type + Member variable name
        public static final int NUM = 10;
        
         Member method :
         Permission modifier +static/final/abstract+ Return type + Method name
27、 Inner class ( The second point is )
    (1) Define a class in a class , This class is called the inner class , Built-in class , Nested class .
    (2) Visit features :
        A: Internal classes can directly access members of external classes , Because inner classes hold references to outer classes ,
           The format is : External class name .this
        B: External classes want to access members of internal classes , Object access must be created .
    (3) The access format of the inner class :
        A: When the inner class is defined in the member position of the outer class , And it's not private , You can directly create internal class objects in other external classes
           Format : External class name . Internal class name   Variable name = new External class objects . Inner class object
             Such as :Outer.Inner in = new Outer().new Inner()
        B: When the inner class is in the member position of the outer class , And be static When decorating
            ** Other external classes have direct access to non static members of static internal classes
               Format :new External class name . Internal class name (). Inner class members
               Such as :new Outer.Inner().function();
            ** External other classes can directly access static members of static internal classes
               Format :new External class name . Internal class name . Inner class members
               Such as :new Outer.Inner.function();
    (4) When to use inner classes ?
         If there is A Classes and B class ,A Class wants to directly access B Class members ,B Such access A Class members ,
         Need to create A Class object to access , This is the time , You can put the A Class is defined as B The inner class of a class .
    (5) The location of the inner class
        A: Member position
            ** Can be private modification (Body,Heart)
            ** Can be static modification .( The members of the external classes it accesses must be static )    
        B: Local location
            ** You can directly access members of external classes , Because it also holds the use of external classes
             You can also access local members directly , But some members use final modification .      
         Be careful : Local inner class cannot be used private and static modification         
    (6) adopt class We can distinguish whether there are inner classes in the file , And the location of the inner class
        Outer$Inner: Member inner class
        Outer$1Inner: Local inner classes
28、 Anonymous inner class ( Shorthand for local inner class ) ( a key )
        (1) Premise : Inherit a class or implement an interface
        ( Be careful not to confuse the premise of anonymous inner class with the premise of polymorphism )
        (2) Format :
            new Parent class name or interface name ()
            {
                 Overriding a parent method or implementing a method in an interface .
                 You can also customize other methods .
            };
        (3) When to define anonymous inner classes ?
             Anonymous inner classes just to simplify writing , Anonymous inner classes have limitations , When defining anonymous inner classes , This type of method does not exceed 3 individual
        (4) The advantages and disadvantages of anonymous inner classes :
             benefits : Simplify code writing
             disadvantages :
                 You can't call your own methods directly
                 Can't perform a strong switch action
                 If there are many methods in this class , Anonymous inner classes are not allowed
29、 Template design pattern :
     When defining functions , Part of the function is certain , Part of it is uncertain , And the definite part uses the uncertain part ,
     Can expose the uncertain part , This is done by subclasses of this class .
     Such as : Find an example of the running time of a program .
30、 abnormal
    (1) Abnormal phenomenon in the process of program operation is called abnormal .
    (2) There are many phenomena that cause the program to run abnormally , therefore , There are a lot of exception objects .
        And these abnormal objects have common content , therefore , It can be extracted continuously . Finally, an abnormal architecture is formed .
        The root class of the exception system is :Throwable
       Throwable:
        |--Error: A big problem , We can't deal with . There's no need to write code to handle . For example, memory overflow .
        |--Exception: A general mistake , We need to write code to deal with .
            |--RuntimeException: Runtime exception , We don't need to deal with this either .
                                 In fact, it's to make him run into problems , And then we come back to modify the code .
    (3) Classification of exceptions         
         There are two kinds of anomalies :
         Exception detected at compile time :
             This exception is at compile time , If not dealt with ( There is no throwing or try), Compile failed .
             The exception is marked , Represents that this can be dealt with .
         Runtime exception ( Compile time does not detect )
             At compile time , No need to deal with , The compiler does not check .
             The occurrence of the anomaly , Suggest not to deal with , Let the program stop . Need to fix the code .
    (4) Characteristics of abnormal system :
         All classes and their subclass objects in the exception system are disposable . That is to say, it can be throw and throws Keyword operation .
    (5)main Method is how to handle exceptions .
        A: stay main Write code to deal with it
        B: hand jvm Deal with it yourself . It's using jvm The default handling method of .
           In fact, it is equivalent to calling an exception object printStackTrace() Method .
    (6)Throwable Class learning
        getMessage(): Get exception information , Return string .
        toString(): Get exception class name and exception information , Return string .
        printStackTrace(): Get exception class name and exception information , And where the exception appears in the program . Return value void.
    (7) Exception handling ·
        A:try...catch...finally
         The basic format :
            try
            {
                 Code with possible exception
            }
            catch( Exception object )
            {    
                 Exception handling code
            }
            finally
            {
                 Release resources
            }
        
         Variant format :
            try...catch
            try...catch...catch...
            try...catch...catch...finally
        ** When multiple exceptions are caught at the same time , Remember a principle :
             Catch the small ones first , Catch the big one again .
        **finally: Forever executed , Unless you quit jvm.System.exit(0);
             Interview questions 2 individual .
            ***:final,finally,finalize difference .
               final Is the ultimate meaning . It can be used to decorate classes , Member variables , Member method .
                The class it modifies cannot be inherited , It modifies variables as constants , The method it modifies cannot be overridden .

               finally: Is the keyword in exception handling .
                The code in it is always executed . A special case : Before executing it jvm sign out .System.exit(0);

               finalize: yes Object A method in class .
                It's in the way the garbage collector calls .

            ***: If catch There is return sentence , finally Will the code in be executed ?
                Is in return front , Still return Then what? ?
                Meeting , stay return Pre execution finally Code inside .
    (8)Exception and RuntimeException The difference between
        A:Exception: A general mistake , We need to write code to deal with .    
        B:RuntimeException: Runtime exception , We don't need to deal with this either .
                        In fact, it's to make him run into problems , And then we come back to modify the code .
             In use throws When you throw one , If the exception belongs to RuntimeException When it comes to systems ,
             We don't have to deal with where we call .(RuntimeException and RuntimeException Subclasses of )
            
             In use throws When you throw one , If the exception belongs to Exception When it comes to systems ,
             We have to process or continue throwing at the call .
    (9) Custom exception
         Define class inheritance Exception perhaps RuntimeException
        1, To make this custom class castable .
        2, Let this class have the common method of abnormal operation .
        class MyExcepiton extends Exception
        {
            MyExcepiton(){}

            MyExcepiton(String message)
            {
                super(message);
            }
        }

        class MyException extends RuntimeException
        {
            MyExcepiton(){}

            MyExcepiton(String message)
            {
                super(message);
            }
        }
    (10)throws and throw The difference between
        A: Yes throws There is no throw.
            Yes throw When , If throw The exception is Exception system , Then there must be throws Declare... On the method .
        B:throws On the declaration of the method , Followed by the exception class name , It can be followed by multiple exception classes , Separated by commas
           throw Used in method bodies , Followed by an exception object name

 


        
In this paper, from :https://blog.csdn.net/hao19980724/article/details/83792516

版权声明
本文为[renlianggee]所创,转载请带上原文链接,感谢

Scroll to Top