java knowledge point accumulation 2

accumulation of knowledge

  • 1. About abstract classes and interfaces:

    • Classes cannot have multiple inheritance but interfaces can;

    • Neither abstract classes nor interfaces can be instantiated, that is, abstract classes cannot be instantiated through new;

    • Abstract classes can contain properties, methods, and constructors. However, the constructor cannot be used for new instances, it can only be used to be called by subclasses;

    • Abstract classes can only be used for inheritance;

    • Abstract methods must be implemented by subclasses.

    • There are only: constants, abstract methods in the interface

    • Interfaces can inherit interfaces (through extends), and multiple inheritance is possible

  • 2. Two-dimensional array:
    • In the definition of a two-dimensional array, the first bracket must have a value, which cannot be empty, but can be 0;

  • 3. About abstract classes:
    • A subclass can only inherit one abstract class, but can implement multiple interfaces;

    • Abstract classes can have constructors, interfaces have no constructors;

    • An abstract class can have ordinary member variables, but an interface cannot have ordinary member variables;

    • Both abstract classes and interfaces can have static member variables, the access rights of static member variables in abstract classes are arbitrary, and interfaces can only be public static final (default);

    • Abstract classes can have no abstract methods, abstract classes can have ordinary methods, and interfaces are all abstract methods;

    • Abstract classes can have static methods, but interfaces cannot have static methods;

  • 4. Important knowledge points about final:
    • The final keyword can be used for member variables, local variables, methods and classes;

    • Final-modified member variables must be initialized at the time of declaration, or initialized in the constructor, otherwise a compilation error will be reported;

    • You cannot assign a final variable again;

    • Local variables must be assigned a value when they are declared;

    • All variables in anonymous classes must be final variables;

    • Final modified methods cannot be overridden;

    • Final modified classes cannot be inherited;

    • Final variables that are not initialized at the time of declaration are called blank final variables, they must be initialized in the constructor, or call this to initialize, otherwise the compiler will report an error

  • 5. When the operation data type is byte, short, int, char, both numbers will be converted to int type, and the result is also int type (when performing +, -, *, /, % operations)
  • 6. Method input parameters:
    • When the input parameter of the method is a basic type, the value is passed, and the modification of the passed value in the method will not affect the variable that is called;

    • When the input parameter of the method is a reference type, the reference address is passed, and the modification of the passed value in the method will affect the variable at the time of the call;

package com.javasm.work3;

import java.util.Arrays;

public class TestMethod {
    public static void main(String[] args) {
        TestMethod method=new TestMethod();
        int b = 1;
        b = method.test1(b);
        System.out.println(b);
        
        int[] arr = {1,2,3};
        method.test2(arr);
        System.out.println(arr[0]);
        System.out.println(arr);
        Arrays.sort(arr);
    }
    
    /**
     * 方法入参是基本数据类型时,传递的是值
     * 方法内对传递的值进行修改时不会影响调用时的变量
     * @param a
     */
    public int test1(int a){
        a=2;
        return a;
    }
    
    /**
     * 方法入参是引用数据类型时,传递的是内存地址引用
     * 方法内对传递的引用进行修改时会影响调用时的变量
     * @param arr1
     */
    public void test2(int[] arr1){
        System.out.println(arr1);
        arr1[0] = 4;
    }
}
  • 7. The ordinary methods of the parent class can be inherited and overridden. I won't explain much. If the child class inherits the parent class, and the child class does not override the parent class's methods, the child class will have methods inherited from the parent class.

    • Static methods can be inherited, but not overridden. If there is a static method in the parent class, and the subclass also has a method with the same method name, parameter type, and number of parameters, and it is also modified with the static keyword, then the method of the subclass will inherit the original parent class. The method is hidden, not overridden. In layman's terms, the method of the parent class and the method of the subclass are two unrelated methods, and which method is called depends on which object is referenced; this kind of parent-child method does not have the property of polymorphism. It is mentioned in "Java Programming Ideas" that "only ordinary method calls can be polymorphic". The following code is an example:
public class StaticTest  
{  
    public static void main(String[] args)  
    {  
        M m = new N();  
        m.output();  
    }  
}  
  
class M  
{  
    public static void output()  
    {  
        System.out.println("M");  
    }  
}  
  
class N extends M  
{  
    public static void output()  
    {  
        System.out.println("N");  
    }  
}  

The result of the above execution is "M", which is called by a reference of type M. If you modify the code in the main method:

N n = new N();

n.output();

Then the result of the execution is "N", which is called by a reference of type N.


  • 8. Why can't this and super keywords be used in static members and static methods?

    • 1. You cannot use this predefined object reference in a static method, even if the operation behind it is also a static member.
      Because this represents the reference to the object that calls this function, and the static method belongs to the class, not It belongs to the object. After the static method is successfully loaded, the object does not necessarily exist
    • 2. Before the question, let's talk about the usage of super:
      • 1. The usage of super is similar to this. This represents a reference to an object of this class, pointing to an object that has been created by this class; while super represents a reference to an object of the parent class, pointing to the object of the parent class;
      • 2. Static takes precedence over object existence;
      • 3. Known from 1. and 2. above:
        because static takes precedence over object existence, the method exists first after the method is statically modified, and the parent class object pointed to by super is used in the method, but the required parent class reference object After the method appears, that is, the object pointed to by super does not, of course, an error will occur.

        To sum up, the super keyword cannot appear in static methods.
    • 3. First of all, you need to understand the difference between objects and classes.
      • this and super are things that belong to the category of objects, while static methods are things that belong to the category of classes
      • All member methods have a default parameter this (even a method with no parameters), as long as it is a member method, the compiler will add this parameter to you, such as:
      • The void method1(){} in Class A is actually like this --------> void method1(A this)

      • void method2(int x){} is actually like this --------> void method2(A this, intx)
        and static methods have nothing to do with objects, so you can't pass the reference of the object to the method at all, so you can't use this

    • 4. If a method is defined as static in a class, it is a static method, that is to say, this method can be called without an object of this class, and calling a static method is "class name.method name"

Since "static methods can be called without objects of this class", and the this and super keywords are both used for objects of this class --- calling a static method without an object of this class clearly shows that: static methods cannot use this and super keywords in

    • 5. The static method is stored in the data segment in the memory. This and super call the application object in the heap space and cannot call the data in the data segment area. Therefore, the this and super keywords cannot be used in static methods.
    • 6. Static methods and static classes do not belong to a single object, but are shared by all objects of the class
      and this represents the current object
    • 7. Things only belong to classes, not to any objects, so THIS and SUPER cannot be used.

  • 9. Conditional operator (ternary operator):
String type = score<60?"不及格":"及格";


int i = (string=="hello"? 10:-1);

int j = (x>0 ? 1:(x>10 ? 2:-1));//多重嵌套

  • 10. Static import is a newly added function in JDK1.5. Its function is to import the static properties of the specified class, so that the static properties can be used directly;
import static java.lang.Math.PI;    //导入Math类的PI属性

  • 11. The equals() method provides the logic to define "object content is equal"

  • 12. The initialization method of the array:

  • static initialization

int [] a = {1,2,5,7,3};    //静态初始化基本类型数组
User[] b = {
    new User(01,"张三"),
    new User(02,"李四"),
    new User(03,"王五")
};                     //静态初始化引用类型数组;
  • Dynamic initialization

int[] a = new int[2];   //动态初始化数组,先分配空间;
a[0] = 1;//给数组元素赋值;
a[1] = 2;//给数组元素赋值;
  • default initialization

int[] a = new int[2];   //默认值:0,0;
boolean[] b = new boolean[2];   //默认值:false,false;
String[] s = new String[2];     //默认值:null,null;

  • 13. The memory of the java virtual machine can be divided into three areas:

  • stack stack

    • Features:
      • (1) The stack describes the memory model of method execution, and each method is called to create a stack frame (storing local variables, operands, method entries, etc.);
      • (2) JVM creates 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 threads and cannot be shared between threads;
      • (4) The storage feature of the stack is FIFO, LIFO ;
      • (5) The stack is automatically allocated by the system, and the speed is fast. The stack is a continuous memory space.
  • heap heap

    • Features:
      • (1) The heap is used to store created objects and arrays (arrays are also objects);
      • (2) The JVM has only one heap, which is shared by all threads;
      • (3) The heap is a discontinuous memory space with flexible allocation and slow speed.
  • Method area method area (located in the heap)

    • Features:
      • (1) JVM has only one method area, which is shared by all threads;
      • (2) The method area is actually a heap, but it is only used to store information related to classes and constants;
      • (3), use the content that is always unchanged or unique in the storage program. (Class information [Class object], static variables, string constants, etc.)
  • 14. When a parameterized constructor is defined in a class, the parameterless constructor no longer exists, and it must be explicitly declared in the class if it is to be used;

  • 15. The main points of inheritance:

    • The parent class is also called super class, base class, etc.;
    • There is only single inheritance in java, there is no multiple inheritance like C++. Multiple inheritance can cause confusion, making inheritance too complicated and the system difficult to maintain;
    • There is no multiple inheritance for classes in java, but multiple inheritance for interfaces;
    • The subclass inherits the parent class and can get all the properties and methods of the parent class (except the constructor of the parent class), but not necessarily direct access (for example, the private properties and methods of the parent class);
    • If you define a class without calling extends, its parent class is: java.lang.Object.
  • 16. The instanceof operator:

    • instanceof is a binary operator, the left is the object, the right is the class; when the object is an object created by the right class or subclass, it returns true; otherwise, it returns false.
      ```java
      public class Test{
      public static void main(String[] args) {
      Student s = new Student();
      System.out.println(s instanceof Person); //Student inherits from Person
      System.out.println( s instanceof Student);
      }
      }

```

  • 17. Logical operators:
operator symbol illustrate
logical and &(and) The result is true only if both operands are true, otherwise it is false
logical or ! (or) One of the two operands is true, the result is true
short circuit with &&(与) As long as one is false, return false directly
short circuit or || (or) As long as one is true, return true directly
logical not ! (No) Negative: !false is true, !true is false
logical XOR ^ (exclusive or) Same as false, different as true
  • Short-circuit and and short-circuit or use the short-circuit method to calculate from left to right. If the value of the logical expression can be determined only by the operand on the left side of the operator, the operand on the right side of the operator will not continue to be calculated, which improves efficiency.

  • 18. Recursive structure

    • Recursion is a common problem-solving method, that is, to gradually simplify the problem. The basic idea of ​​recursion is to "call itself", a method using recursion will call itself directly or indirectly.
    • Using recursion can solve some complex problems with simple programs. For example: calculation of Fibonacci sequence, Tower of Hanoi, quick sort, etc.
    • The recursive structure consists of two parts:
      • (1) Define the recursive header. Answer: When not to call its own method. If there is no head, it will fall into an infinite loop, which is the end condition of the recursion .
      • (2) Recursive body. Answer: When do you need to call your own method.
public class Test22{
    public static void main(String[] args) {
        long d1 = System.currentTimeMillis();
        System.out.printf("%d阶乘的结果:%s%n",10,factorial(10));
        long d2 = System.currentTimeMillis();
        System.out.printf("递归费时:%s%n",d2-d1);   //耗时:32ms
    }
    /** 求阶乘的方法*/
    static long factorial(int n) {
        if(n == 1) {//递归头
            return 1;
        }else{//递归体
            return n*factorial(n - 1);  //n! = n*(n - 1)!
        }
    }
}
    • Recursive flaws:
      • Simple programs are one of the advantages of recursion, but recursive calls will occupy a lot of system stacks and consume a lot of memory. When there are many levels of recursive calls, the speed is much slower than loops, so be careful when using recursion.
    • Precautions
      • Any problem that can be solved recursively can also be solved iteratively (loops). Recursion can be used when the recursive method can increase the natural reflection of the problem, is easy to understand and debug, and does not emphasize the efficiency problem;
      • Try to avoid using recursion when high performance is required. Recursive calls take time and memory.
  • 19. Upward automatic transformation, upward forced transformation:

public class TestPolm {
    public static void main(String[] args) {
        
        Animal cat = new Cat();//自动向上转型
        animalCry(cat);
        
        Cat cat2 = (Cat)cat; //强制向下转型
    }
    
    static void animalCry(Animal a){
        a.shut();
    }
}

class Animal{
    public void shut(){
        System.out.println("叫了一下!");
    }
}

class Dog extends Animal{//继承条件满足
    public void shut(){//方法重写条件满足
        System.out.println("汪汪汪");
    }
}

class Cat extends Animal{//继承条件满足
    public void shut(){//方法重写条件满足
        System.out.println("喵喵喵");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324862137&siteId=291194637