Summary of Java knowledge points "Basic"

Small chat : This article mainly edits small details or knowledge supplements that Xiaobai feels are important and easy to forget Javawhen . Thinking that it will be very helpful for learning and using Javait , I will record it a little bit. The knowledge points with more content will be written in this column, so here are all small tipsones.

The entire Java language part, I will divide it into "Basic", "Efforts" and "Supplement", and the supplement may also be updated from time to time~ This article is "Basic".

All sections so far:

Summary of Java knowledge points "Basic"

Summary of Java knowledge points "Effort Part 1"

Summary of Java knowledge points "Effort Part II"


1. Java JRE and JDK

  • JRE (Java Runtime Environment): It is the runtime environment of Javathe program , including JVMthe core class library required for runtime.
  • JDK (Java Development Kit): is a Javaprogram development kit, including JREtools and tools used by developers.

If we want to run an existing Java program, we only need to install it JRE, and if we want to develop a brand new Javaprogram , we must install it JDK.

Tips:

The relationship between the three: JDK > JRE > JVM


2. Java data type conversion

  • Automatic conversion : When different types of operations are performed, the result will take a type with a large value range , so the return value must be received with a large value, otherwise an error will be reported when compiling.

    • Conversion Order Rules

      A type with a small range is promoted to a type with a large range. When byte, , shortand charare operated, they are directly promoted to int , which javais automatically executed.

      byteshortchar‐‐>int‐‐>long‐‐>float‐‐>double
      
  • cast :

    Forcing a type with a large value range to a type with a small value range requires us to perform it manually.

    • Note:
      • When converting floating point to integer, cancel the decimal point directly, which may cause data loss of precision.
      • intForced conversion shortto cut off 2 bytes may cause data loss.

3. Java constant optimization mechanism

  •  在常量进行运算的时候,它的值是固定不变的。所以 `java` 虚拟机会自动进行运算(就是上面的自动隐式转换)。
    
  •  然后判断是否超出了取值范围,如果没有超出就正常赋值。
    
public static void main(String[] args) {
    
    
    //short类型变量,内存中2个字节 
    short s = 1;
    /*出现编译失败 s和1做运算的时候,1是int类型,s会被提升为int类型 s+1后的结果是int类型,将结果在赋值会short类型时发生错误 short内存2个字节,int类型4个字节 必须将int强制转成short才能完成赋值 */
    s = s + 1; // 编译失败 
    s = (short)(s+1); // 需要手动强制,编译成功  
    System.out.println(s1);  // 2
}

4. When using +=, -=will automatically cast the result type of the operation to the type holding the result

  • What's the meaning? From the Java constant optimization mechanism, we know the application of type implicit conversion, or this example
public static void main(String[] args) {
    
    
    // 例子一
    short s1 = 1;
    // s1 = s1 + 1; // short类型在进行运算时会自动提升为int类型。Java编译检测报错,无关结果是否溢出
    s1 += 1;    // 正确写法,它的机制就是先将结果算出,再将结果强制转换为持有结果的类型,溢出就为负
    System.out.println(s1);  // 2

    // 例子二(溢出情况)
    short a = 32767;
    short b = 1;
    b += a;
    System.out.println(b);  // -32768
}

5. The difference between member variables and local variables

the difference Member variables local variable
The position in the class is different (emphasis) in class, outside method In a method or on a method declaration (formal parameters)
The scope of action is different (emphasis) in class method
Differences in initialization values ​​(emphasis) has a default value There is no default value. must first be defined, assigned, and finally used
The location in memory is different (emphasis) heap memory stack memory
The life cycle is different (understand) Exists as the object is created and disappears as the object disappears Exists as the method is called and disappears as the method is called

6. Stack, heap, method area (overview)

The memory of the Java virtual machine can be divided into three areas: the stack stack, the heap , heapand the method area method area. The method area is actually inside the heap. JVMThe overall memory structure is stack and heap.

  • stack stack

    1. The stack describes the memory model of method execution. Each method is called to create a stack frame (storage of local variables, operands, method exit, etc.)
    2. JVMCreate a stack for each thread to store the information of the thread execution method (actual parameters, local variables, etc.)
    3. The stack is private to the thread and cannot be shared between threads
    4. The storage characteristic of the stack is "first in, last out, last in first out" (magazine effect)
    5. The stack is automatically allocated by the system and is fast. The stack is a contiguous memory space
  • heap heap

    1. The heap is used to store created objects and arrays (arrays are also objects)
    2. JVMThere is only one heap, shared by all threads
    3. The heap is a discontinuous memory space with flexible allocation and slow speed!
  • Method area method area (also called static area)

    1. JVMThere is only one method area, which is shared by all threads!
    2. The method area is actually a heap, which is only used to store information related to classes and constants!
    3. It is used to store the constant or unique content in the program. (class information [ Classobject], static variables, string constants, etc.)

7. Standard code - JavaBean

JavaBeanIt is a standard specification for Javalanguage writing classes. JavaBeanA class that conforms to requires that the class must be specific and public, and has a parameterless constructor, and provides setand getmethods for manipulating member variables.

Attribute names conform to this pattern, and other Javaclasses can discover and manipulate these JavaBeanattributes through the introspection mechanism (reflection mechanism).

  • format example
package Demo;

/**
 * @Author 白忆宇
 */
public class Fruits {
    
    
    private String name;
    private String color;

    /**
     * 不写构造方法默认存在无参数的构造方法
     */
    public Fruits() {
    
    
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getColor() {
    
    
        return color;
    }

    public void setColor(String color) {
    
    
        this.color = color;
    }
}

8. Comprehensive and brief understanding of packaging concepts

  • Function : a protective barrier between codes, preventing the code and data of this class from being randomly accessed by other classes. To access the data of this class, you must pass the specified method. Proper encapsulation can make the code easier to understand and maintain, and also enhance the security of the code.

  • How to achieve encapsulation characteristics

    • (1) private keyword (main)

      Member variables and member methods modified by private can only be accessed in this class. Provide a pair of getXxx methods and setXxx methods corresponding to the member variables that need to be accessed.

    • (2) this keyword (encapsulation optimization 1)

      thisRepresents the reference (address value) of the current object of the class, that is, the reference of the object itself.
      Note: the method is called by which object, and the in the thismethod represents that object. That is, whoever is calling thisrepresents that person.

    • (3) Construction method (encapsulation optimization 2)

      When an object is created, the constructor is used to initialize the object and assign initial values ​​to the member variables of the object.
      Note: All classes have constructors, no matter whether they are custom constructors or not, because a parameterless constructor is Javaautomatically provided. Once the constructor is defined, Javathe automatically provided default parameterless constructor will be invalid.


9. A comprehensive and brief understanding of the concept of inheritance

  • Function (benefit) : Improve code reusability, simpler code structure; relationship between classes is created, which is the premise of polymorphism.
  • Principle : The subclass inherits the attributes and behaviors of the parent class , so that the subclass object has the same attributes and behaviors as the parent class. Subclasses can directly access non-private properties and behaviors in the parent class.
  • Features : Only single inheritance is supported. But it can be multi-level inheritance (inheritance system)
  • Disadvantages : The coupling between classes is too strong, the concept of "loose coupling" in the code world is very important, don't affect the whole body by a single hair.

10. The super and this keywords

keywords meaning
super Represents the storage space identifier of the parent class (can be understood as a reference to the father)
this Represents the reference of the current object (whoever calls it represents who)
  • usage

    • visiting member

      this.Member variable - of this class

      super.Member variable--of the parent class

      this.Member method name() ‐‐ of this class

      super.Member method name() ‐‐ of the parent class

    • access constructor

      this(…) - the constructor of this class

      super(…) ‐‐ The constructor of the parent class


11. Parent class space is better than child class object initialization

Every time a subclass object is created, the parent class space is initialized first, and then the subclass object itself is created. The purpose is that the subclass object contains its corresponding parent class space, so it can contain the members of its parent class. If the parent class members are not privatemodified , the subclass can freely use the parent class members. When the code is reflected in the call of the constructor of the subclass, the constructor of the parent class must be called first.

  • simple interview questions

    • Problem: A subclass inherits a parent class, and another class initializes and creates this subclass to use: subclass no-argument construction method, subclass static{}code and parent class no-argument construction method, parent class static{}code block, their What is the order of execution?

    • Answer: parent class static code block > subclass static code block > parent class construction method > subclass construction method

    • code explanation

      package Demo;
      
      /**
       * @Author 白忆宇
       */
      class Dad {
              
              
          static {
              
              
              System.out.println("父类 static 初始化");
          }
          public Dad() {
              
              
              System.out.println("父类构造方法初始化");
          }
      }
      
      class Son extends Dad {
              
              
          static {
              
              
              System.out.println("子类 static 初始化");
          }
          public Son() {
              
              
              System.out.println("子类构造方法初始化");
          }
      }
      
      public class Main {
              
              
          public static void main(String[] args) {
              
              
              Son son = new Son();
          }
      }
      
      // 输出
      父类 static 初始化
      子类 static 初始化
      父类构造方法初始化
      子类构造方法初始化
      

12. Comprehensive and brief understanding of abstract classes

  • Function (benefit) : As the name suggests, it provides an abstract framework for subclass methods, because the implementation of this method will be different for different subclasses, inherit abstraction, and the specific implementation is done by subclasses. To put it bluntly, this kind of benefit is to cater to the characteristics of object java-oriented , and have an additional development idea. (Xiaobai later felt gothat the great simplicity is also a kind of truth, and it is more difficult to make the complexity simple)

  • Definition : modifier abstract return value type method name (parameter list);

    public abstract void run();
    
  • Note : Subclasses that inherit abstract classes must override all abstract methods of the parent class . Otherwise, the subclass must also be declared abstract. In the end, there must be a subclass that implements the abstract method of the parent class, otherwise, objects cannot be created from the initial parent class to the final subclass, which is meaningless.

  • other precautions

    An abstract class cannot create an object . If it is created, the compilation will fail and an error will be reported. Only objects of its non-abstract subclasses can be created.

    理解:假设创建了抽象类的对象,调用抽象的方法,而抽象方法没有具体的方法体,没有意义。 
    

    In an abstract class, there can be a constructor, which is used for initializing the members of the parent class when the subclass creates an object.

    理解:子类的构造方法中,有默认的super(),需要访问父类构造方法。 
    

    Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.

    理解:未包含抽象方法的抽象类,目的就是不想让调用者创建该类对象,通常用于某些特殊的类结构设计。 
    

    The subclass of the abstract class must rewrite all the abstract methods in the abstract parent class, otherwise, the compilation will fail and an error will be reported. Unless the subclass is also an abstract class.

    理解:假设不重写所有抽象方法,则类中可能包含抽象方法。那么创建对象后,调用抽象的方法,没有意义。 
    
  • Simple use example: (you don’t need to read it)

    package Demo;
    
    /**
     * @Author 白忆宇
     */
    abstract class Animal {
          
          
        private String animalName;
    
        public String getAnimalName() {
          
          
            return animalName;
        }
        public void setAnimalName(String animalName) {
          
          
            this.animalName = animalName;
        }
        /**
         * 抽象方法action()
         */
        abstract void action();
    }
    
    class Dog extends Animal {
          
          
        @Override
        void action() {
          
          
            System.out.println("我是" + super.getAnimalName() + ",我爱摇尾巴");
        }
    }
    
    class Cat extends Animal {
          
          
        @Override
        void action() {
          
          
            System.out.println("我是" + super.getAnimalName() + ",我爱喵喵叫");
        }
    }
    
    public class Main {
          
          
        public static void main(String[] args) {
          
          
            Animal dog = new Dog();
            dog.setAnimalName("狗");
            dog.action();
            Animal cat = new Cat();
            cat.setAnimalName("猫");
            cat.action();
        }
    }
    
    // 输出
    我是狗,我爱摇尾巴
    我是猫,我爱喵喵叫
    

13. Comprehensive and brief understanding of the interface

  • Role : The biggest benefit is to improve code maintainability. For example: the control class calls the implementation class method through the interface. When modifying the implementation class, there is no need to move the control class. Only the interface implementation needs to be modified. This is the case for the spring development model framework. The specific principles can be understood in combination with Java's object-oriented dependency inversion design principles.

  • Introduction : It is a reference type in the Java language, which is a collection of methods. If the inside of the class encapsulates member variables, construction methods and member methods, then the inside of the interface mainly encapsulates methods, including abstract methods (JDK 7 and before ) ), default and static methods (JDK 8), private methods (JDK 9).

  • Definition : public interface interface name {}

    public interface animal {
          
          
        //抽象方法:使用 abstract 关键字修饰,可以省略,没有方法体。该方法供子类实现使用。
        public abstract void eat();
        //静态方法:使用 static 修饰,供接口直接调用。
        public static void sleep();
        //私有方法或私有静态方法:使用 private 修饰,供接口中的默认方法或者静态方法调用。
        private (static) void run();
        //默认方法:使用 default 修饰,不可省略,供子类调用或者子类重写。
        public default void fight();
    }
    
  • Caution

    • A non-abstract subclass implementing an interface must implement all the abstract methods in the interface ; a class can implement multiple interfaces
    • Implement interface vsinheritance class: a class can only inherit one parent class, while implementing multiple interfaces at the same time
    • When a class inherits a parent class and implements several interfaces, the member method in the parent class has the same name as the default method in the interface, and the subclass chooses to execute the member method of the parent class nearby.
  • Other tips

    • In the interface, member variables cannot be defined, but constants can be defined, and their values ​​cannot be changed. By default, they are decorated with public static final.
    • In an interface, there is no constructor, and objects cannot be created.
    • In the interface, there is no static code block.

14. Polymorphic comprehensive and brief understanding

  • Function : For example: no matter how many subclasses appear in the future, we don't need to write getXxx/setXxx methods, and can be completed directly by using the parent class getXxx/setXxx. It can make programming simpler and have good extensions .

  • Definition : Polymorphism is the third major feature of object-oriented after encapsulation and inheritance . It refers to the same behavior, with several different manifestations. For example: the activities of creatures: people walking, fish swimming, birds flying...

  • Use : parent class type variable name = new subclass object; variable name. method name();

    Fu f = new Zi(); 
    f.method();
    
  • other attention

    • Inherit or implement [choose one of the two]
    • Method rewriting [meaningful expression: no rewriting, meaningless]
    • The parent class reference points to the subclass object [Format]
    • The parent class reference, if you want to call the unique method of the subclass, you must do downcasting. (polymorphic minor restrictions)
  • Example of use (optional)

    package Demo;
    
    /**
     * @Author 白忆宇
     */
    abstract class Fruits {
          
          
        public abstract void color();
    }
    
    class Banana extends Fruits {
          
          
        @Override
        public void color() {
          
          
            System.out.println("黄色~");
        }
    }
    
    class Grape extends Fruits {
          
          
        @Override
        public void color() {
          
          
            System.out.println("紫色~");
        }
    }
    
    public class Main {
          
          
        public static void main(String[] args) {
          
          
            Banana banana = new Banana();
            Grape grape = new Grape();
    
            getFruitsColor(banana);
            getFruitsColor(grape);
        }
    
        public static void getFruitsColor(Fruits fruit) {
          
          
            fruit.color();
        }
    }
    
    // 输出
    黄色~
    紫色~
    

15. final (interview test center)

Features : Unchangeable. Can be used to decorate classes, methods and variables.

Class : The modified class cannot be inherited.

Method : The decorated method cannot be overridden. And JVMwill try to inline it to run more efficiently.

Variable : Modified variable cannot be reassigned. If the reference is modified, it means that the reference is immutable, and the content pointed to by the reference is variable.

Constant : The modified constant name generally has a writing standard, and all letters are capitalized. It will be stored in the constant pool during the compilation phase.

  • final about reordering rules
    • A write to a finalfield and the subsequent assignment of a reference to the constructed object to a reference variable cannot be reordered.
    • There is no reordering between the initial read of a reference to an object containing finalthe field , and the subsequent initial read of the field.final

16. Permission Modifiers

public : public.

protected : protected

default : the default

private : private

public protected default private
in the same class
In the same package (subclass and unrelated class)
Subclasses of different packages
Unrelated classes in different packages
  • practical advice
    • Member variable usage private, hiding details.
    • The construction method is used publicto facilitate the creation of objects.
    • The member method depends on the permission requirements, generally usedpublic

17. Java primitive types and wrapper types

The eight basic data types are their encapsulation classes

basic type Defaults package type
short 0 Short
int 0 Integer
float 0.0 Float
double 0.0 Double
long 0 Long
byte 0 Byte
boolean false Boolean
char \u0000 Character
  • The default value of the member variable encapsulation type isnull
  • When the basic data type is declared, the system will automatically allocate space for it, while the reference type is only allocated a reference space when it is declared, and it must be instantiated to open up the data space before it can be assigned.

18. Rewrite

  • Override definition (Override)

    If a member method with the same name appears in the parent class of the subclass , the access at this time is a special case called method rewriting ( Override).

    When the same method as the parent class appears in the subclass (the return value type, method name and parameter list are the same), there will be an overriding effect, also known as rewriting or duplication. Declare unchanged, reimplement .

    The overridden method is specified and annotated @Override(optional).

    • Example of use (optional)
    package Demo;
    
    class Dad {
          
          
        public void action(String action) {
          
          
            System.out.println("爸爸爱"+action);
        }
    }
    
    class Son extends Dad {
          
          
        public Son() {
          
          
        }
    
        public void action() {
          
          
            System.out.println("我是儿子在睡觉");
        }
        
        @Override
    	//重写的好处可以在原来的基础上修改和添加操作
        public void action(String action) {
          
          
            super.action(action);
            System.out.println("儿子爱"+action);
        }
    
    }
    
    public class Main {
          
          
        public static void main(String[] args) {
          
          
            Son son1 = new Son();
            son1.action();
            son1.action("睡觉");
        }
    }
    
    
    输出:
    我是儿子在睡觉
    爸爸爱睡觉
    儿子爱睡觉
    
  • Summarize

    • The method name, parameter list, and return type (except that the return type of the method in the subclass is the subclass of the return type in the parent class) must be the same

    • Subclass methods override parent class methods, and must ensure that the permissions are greater than or equal to the parent class permissions. (For example, when it is a subclass default, the parent class cannot be public)

    • When rewriting, super.parent class member method can be called in the method, which means calling the member method of the parent class.


19. Overload

  • Overload definition (Overload)

    In a class, methods with the same name are considered overloaded if they have different parameter lists ( different parameter types, different numbers of parameters, or even different order of parameters ). At the same time, overloading has no requirement on the return type, which can be the same or different, but the overload cannot be judged by whether the return type is the same .

    • Example of use (optional)
    package Demo;
    
    /**
     * @Author 白忆宇
     */
    
    class Person {
          
          
        public void sayHello() {
          
          
            System.out.println("I say Hello");
        }
        
        public void sayHello(String who) {
          
          
            System.out.println(who + " say Hello");
        }
    }
    
    public class Main {
          
          
        public static void main(String[] args) {
          
          
            Person person = new Person();
            person.sayHello();
            person.sayHello("Tom");
        }
    
    }
    // 输出
    I say Hello
    Tom say Hello
    
  • Summarize

    • Overloading Overloadis a manifestation of polymorphism in a class
    • Overloading requires different parameter lists for methods with the same name ( parameter type, number of parameters and even parameter order )
    • When overloading, the return value types can be the same or different. The return type cannot be used as the criterion for distinguishing from overloading
    • Rewriting occurs in parent classes and subclasses, and overloading is a different form of expression defined in the same class

20. Identifiers and keywords

Identifiers are the names programmers give programs, classes, variables, and methods.

A keyword is a name identified internally by the Java language and is a special identifier.

Javacommon keywords

type keywords
Access control private、protected、public
Classes, Methods and Variables abstract、new、class、static、extends、final、implements、interface、native、strictfp、synchronized、transient、volatile
program control break、for、continue、instanceof、return、do、while、if、else、switch、case、default
error handling try、catch、throw、throws、finally
package related import、package
basic type boolean、char、byte、double、float、int、long、short、null、true、fasle
variable reference super、this、void
reserved word goto、const

21. The difference between == and equals

  • ==

Primitive data types ==compare values, and reference data types ==compare memory addresses.

  • equals()

Its function is also to judge whether two objects are equal, and it cannot be used to compare variables of basic data types. equals()Methods exist in Objectthe class , Objectwhich is the direct or indirect parent class of all classes. And its default implementation is ==, of course, when defining a class, equals()the method

// 默认实现
public boolean equals(Object obj) {
    
    
    return (this == obj);
}
  • equals method in String

Because Sringis not a basic type, the original comparison is the address value, but it is special, the methodString in the class was originally rewritten, and changed to the value of the comparison object. equalsWhen creating an object of Stringtype , the virtual machine will look in the constant pool for an object with the same value as the value to be created, and if so, assign it to the current reference. If not, recreate an Stringobject .



essay

insert image description here

Guess you like

Origin blog.csdn.net/m0_48489737/article/details/127183358