JavaSE learning notes - inner class and String class

JavaSE learning notes (5) -- inner class and String class

1, Internal class foundation

Turn from Rookie tutorial

In Java, you can define a class in another class or a method. Such a class is called an inner class. Generally speaking, there are four kinds of inner classes in a broad sense: member inner class, local inner class, anonymous inner class and static inner class. Let's take a look at the usage of these four inner classes.

1. Member internal class

Member inner class is the most common inner class. It is defined to be located inside another class, as follows:

class Circle {
    double radius = 0;
     
    public Circle(double radius) {
        this.radius = radius;
    }
     
    class Draw {     //Inner class
        public void drawSahpe() {
            System.out.println("drawshape");
        }
    }
}

In this way, the class Draw looks like a member of the class Circle, and the Circle is called the outer class. Member inner classes have unconditional access to all member properties and member methods of outer classes (including private members and static members).

class Circle {
    private double radius = 0;
    public static int count =1;
    public Circle(double radius) {
        this.radius = radius;
    }
     
    class Draw {     //Inner class
        public void drawSahpe() {
            System.out.println(radius);  //private member of an external class
            System.out.println(count);   //Static members of external classes
        }
    }
}

However, it should be noted that when a member internal class has a member variable or method with the same name as the external class, the hidden phenomenon will occur, that is, by default, members of the member internal class are accessed. If you want to access a member with the same name of an external class, you need to access it in the following form:

External class. this. Member variable
 External class. this. Member method

Although the inner class of a member can access the members of the outer class unconditionally, the outer class does not want to access the members of the inner class of a member at will. In an external class, if you want to access members of a member's internal class, you must first create an object of the member's internal class, and then access it through a reference to the object:

class Circle {
    private double radius = 0;
 
    public Circle(double radius) {
        this.radius = radius;
        getDrawInstance().drawSahpe();   //You must create an object of a member's inner class before accessing it
    }
     
    private Draw getDrawInstance() {
        return new Draw();
    }
     
    class Draw {     //Inner class
        public void drawSahpe() {
            System.out.println(radius);  //private member of an external class
        }
    }
}

Member inner class is dependent on outer class, that is to say, if you want to create an object of member inner class, you must have an object of outer class. The general way to create class objects within members is as follows:

public class Test {
    public static void main(String[] args)  {
        //The first way:
        Outter outter = new Outter();
        Outter.Inner inner = outter.new Inner();  //Must be created through the outer object
         
        //The second way:
        Outter.Inner inner1 = outter.getInnerInstance();
    }
}
 
class Outter {
    private Inner inner = null;
    public Outter() {         
    }
     
    public Inner getInnerInstance() {
        if(inner == null)
            inner = new Inner();
        return inner;
    }
      
    class Inner {
        public Inner() {             
        }
    }
}

Internal classes can have private access, protected access, public access and package access. For example, in the above example, if the Inner class of a member is decorated with private, it can only be accessed inside the external class. If it is decorated with public, it can be accessed anywhere. If it is decorated with protected, it can only be accessed under the same package or inheriting the external class. If it is the default access right, it can only be accessed under the same package. This is a little different from external classes, which can only be modified by two permissions: public and package access. I personally understand that because the Inner class of a member looks like a member of an outer class, it can have multiple permission modifiers like a member of a class.

2. Local internal class

A local inner class is a class defined in a method or a scope. The difference between it and a member inner class is that the access of the local inner class is limited to the method or the scope.

class People{
    public People() {
         
    }
}
 
class Man{
    public Man(){
         
    }
     
    public People getWoman(){
        class Woman extends People{   //Local inner class
            int age =0;
        }
        return new Woman();
    }
}

 

Note: just like a local variable in a method, a local inner class cannot have public, protected, private, and static modifiers.

3. Anonymous inner class

Anonymous inner class should be the most commonly used when we write code. It is not only convenient to use anonymous inner class when writing code for event listening, but also easier to maintain the code. The following code is an Android event monitoring code:

scan_bt.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub         
    }
});
 
history_bt.setOnClickListener(new OnClickListener() {
     
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
         
    }
});

This code sets the listener for two buttons, in which anonymous inner classes are used. In this Code:

new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
         
    }
}

Is the use of anonymous inner classes. In the code, you need to set the listener object for the button. Using anonymous inner class can generate a corresponding object when implementing the method in the parent class or interface, but only if the parent class or interface exists first. Of course, it is also possible to write like the following method, which has the same effect as using anonymous inner class above.

private void setListener()
{
    scan_bt.setOnClickListener(new Listener1());       
    history_bt.setOnClickListener(new Listener2());
}
 
class Listener1 implements View.OnClickListener{
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub             
    }
}
 
class Listener2 implements View.OnClickListener{
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub             
    }
}

Although this method can achieve the same effect, it is both lengthy and difficult to maintain, so anonymous inner class method is generally used to write event monitoring code. Similarly, anonymous inner classes cannot have access modifiers and static modifiers.

Anonymous inner class is the only class without a constructor. Because there is no constructor, the scope of anonymous inner class is very limited. Most anonymous inner classes are used for interface callback. Anonymous inner class is automatically named as outer $1.class by the system when compiling. Generally speaking, anonymous inner class is used to inherit other classes or implement interfaces. It does not need to add additional methods, but only implements or rewrites the inherited methods.

4. Static internal class

Static inner class is also a class defined in another class, except that there is a keyword static in front of the class. Static internal classes do not need to rely on external classes, which is similar to the static member properties of classes, and it cannot use non static member variables or methods of external classes, which is well understood, because in the absence of objects of external classes, objects of static internal classes can be created. If access to non static members of external classes is allowed, there will be conflicts because A non static member of an external class must be attached to a specific object.

public class Test {
    public static void main(String[] args)  {
        Outter.Inner inner = new Outter.Inner();
    }
}
 
class Outter {
    public Outter() {      
    }
     
    static class Inner {
        public Inner() {    
        }
    }
}

Class String

  1. The String class is also called an immutable character sequence.

  2. String is located in the java.lang package. Java programs import all classes under the java.lang package by default.

  3. Java string is a sequence of Unicode characters. For example, the string Java is composed of four Unicode characters' J ',' a ',' v ', and' a '.

  4. Java does not have a built-in String type, but provides a predefined class String in the standard Java class library. Each String enclosed in double quotation marks is an instance of the String class.
  5. Java allows the use of the "+" symbol to connect two strings.

Instance of String class

String e = ""  ; // Empty string
String greeting = " Hello World ";

String connection

String s1 = "Hello";
String s2 = "World! ";
String s = s1 + s2; //HelloWorld!

The n-sign "+" connects two strings in a given order, and in exactly the given form.

n-when one of the operands on both sides of the "+" operator is of string type, the system will automatically convert another operand to a string and then connect.

"+" connector

int age = 18;
String str = "age is" + age;  //str is assigned "age is 18"
//This feature is often used in output statements:
System.out.println("age  is" + age);

Constant pool

In the memory analysis of Java, we often hear about the description of "constant pool". In fact, there are three types of constant pools:

1. Global string constant pool

The contents stored in the global string constant pool are stored in the String Pool after the class is loaded. There is only one copy in each VM, and the reference value of the string constant is stored (the string object instance is generated in the heap).

2. class constant pool

Class constant pool is available for each class during compilation. During compilation, it stores constants (text strings, final constants, etc.) and symbol references.

3. Runtime constant pool

The runtime constant pool transfers the symbol reference value of each class constant pool to the runtime constant pool after the class loading is completed, that is to say, each class has a runtime constant pool. After the class is parsed, the symbol reference is replaced with a direct reference, consistent with the reference value in the global constant pool.

Constant pool example

String str1 = "abc";
String str2 = new String("def");
String str3 = "abc";
String str4 = str2.intern();
String str5 = "def";
System.out.println(str1 == str3);// true
System.out.println(str2 == str4);// false
System.out.println(str4 == str5);// true

In the example, after compiling, some symbol references are stored in the class constant pool of the class, and then after the class is loaded, the symbol references stored in the class constant pool are transferred to the runtime constant pool. After verification and preparation, the instance object (that is, the "abc" instance object pointed to by str1 in the above example) that resides in the string is generated in the heap, and then The references of objects are stored in the global String Pool, that is, String Pool. At last, in the resolution phase, to replace the symbol references in the runtime constant pool with direct references, you need to query the String Pool directly to ensure that the reference values in the String Pool are consistent with those in the runtime constant pool, which is probably the whole process.

Back to the example program, now it's easy to explain the memory allocation process of the whole program. First, there will be an "abc" instance in the heap, and a reference value of "abc" will be stored in the global String Pool, and then two instances will be generated when running the second sentence, one is the instance object of "def", and a reference value of "def" will be stored in the String Pool, and One is an instance object of "def" from new, which is different from the above one. When parsing str3, look up String Pool, which contains a global resident string reference of "abc". Therefore, the reference address of str3 is the same as the existing one. str4 calls the intern() function when it is running, and returns the reference value of "def" in String Pool. If The reference value of str2 is not added. Here, the reference value of "def" already exists in String Pool, so return the reference value of "def" added to String Pool when new str2 is added. Finally, str5 also points to the reference value of "def" existing in String Pool when parsing. After such analysis, the result is easy to understand.

Common methods of String class

Turn from Shangxuetang notes

The String class is our most commonly used class. We must be very familiar with String class methods! We list common methods, please be familiar with them.

List of common methods of String class

Common method 1 of String class

public class StringTest1 {
    public static void main(String[] args) {
        String s1 = "core Java";
        String s2 = "Core Java";
        System.out.println(s1.charAt(3));//Extract characters with subscript 3
        System.out.println(s2.length());//Length of string
        System.out.println(s1.equals(s2));//Compare two strings for equality
        System.out.println(s1.equalsIgnoreCase(s2));//Compare two strings (case ignored)
        System.out.println(s1.indexOf("Java"));//Whether Java is included in string s1
        System.out.println(s1.indexOf("apple"));//Does the string s1 contain apple
        String s = s1.replace(' ', '&');//Replace the space in s1 with&
        System.out.println("result is :" + s);
    }
}

The execution result is as shown in the figure:

Common method 2 of String class

public class StringTest2 {
    public static void main(String[] args) {
        String s = "";
        String s1 = "How are you?";
        System.out.println(s1.startsWith("How"));//Start with How
        System.out.println(s1.endsWith("you"));//End with you or not
        s = s1.substring(4);//Extract substring: from the beginning of subscript 4 to the end of the string
        System.out.println(s);
        s = s1.substring(4, 7);//Extract substring: subscript [4, 7) does not include 7
        System.out.println(s);
        s = s1.toLowerCase();//Turn lowercase
        System.out.println(s);
        s = s1.toUpperCase();//Turn capitalization
        System.out.println(s);
        String s2 = "  How old are you!! ";
        s = s2.trim();//Remove spaces at the beginning and end of the string. Note: the space in the middle cannot be removed
        System.out.println(s);
        System.out.println(s2);//Because String is immutable, s2 remains unchanged
    }
}

The execution result is as shown in the figure:

Judgment of string equality

  1. The equals method is used to detect whether the contents of two strings are equal. If the contents of the string s and t are equal, s.equals(t) returns true, otherwise false.

  2. To test whether two strings are equal except for case differences, you need to use the equalsIgnoreCase method.

  3. Do not use '= =' to determine whether the strings are equal.

Ignore case string comparison

"Hello".equalsIgnoreCase("hellO");//true

String comparison "= =" with equals() method

public class TestStringEquals {
    public static void main(String[] args) {
        String g1 = "Beijing shangxue school";
        String g2 = "Beijing shangxue school";
        String g3 = new String("Beijing shangxue school");
        System.out.println(g1 == g2); // true points to the same string constant object
        System.out.println(g1 == g3); // False G3 is a newly created object
        System.out.println(g1.equals(g3)); // True string contents in G1 and g3 are the same
    }
}

The execution result is as shown in the figure:

The memory analysis of the example is shown as follows:

Tags: Java Android

Posted on Fri, 07 Feb 2020 10:02:20 -0500 by rayk