Write it up front

This project has set up a flag since the end of 20 years. After several years of study, I have a new understanding of many knowledge points when I look back. So while looking for internship preparation, combined with the previous learning reserve, to create a Java open source knowledge project mainly for fresh graduates and beginners, focus on Java rear end questions + analysis + key knowledge details + selected articles of the open source project, I hope it can accompany you and I have been progress!

Note: THIS project I do have a lot of attention to do, the content is all I refer to many bloggers (indicated source), materials, N books, and combined with their own understanding, re-drawing, re-organization language and so on. It is inevitable that individual efforts will be weak or inadequate, but there will always be updates/improvements. Every Star is an encouragement to me! I hope you enjoy it.

Note: all the pictures involved are not used in the network map bed, the article is open source to provide you.

Project name: Java-Ideal-interview

Github address: Java-Ideal-interview-github

Gitee address: Java-Ideal-interview-Gitee

In continuous update, online reading will be provided in the later stage, if you think Gitee or Github reading inconvenience, can be cloned to local with Typora and other editors comfortable reading

If the Github clone speed is too slow, you can use the Gitee repository in China

  • Java object oriented
    • 1. Classes and objects
      • 1.1 What is Process Orientation? What is object oriented?
        • 1.1.1 Can you give an example of your understanding of process orientation and object orientation
        • 1.1.2 Advantages and disadvantages of procedural and object orientation
      • 1.2 Explain the relationship and understanding of classes, objects, member variables and member methods
      • 1.3 What is the difference between a member variable and a local variable?
        • 1.3.1 Why are local variables in the stack and not the heap
      • 1.4 Access modifier public, private, protected, and no write (default)
      • What does the 1.5 class do when it is initialized?
      • 1.6 What is the function of the static keyword?
        • 1.6.1 What are Static methods
        • 1.6.2 What are Static variables
        • 1.6.3 What is a Static Code Block
    • 2. Three characteristics of object orientation
      • 2.1 packaging
      • 2.2 inheritance
      • 2.3 polymorphic
    • 3. The other
      • 3.3 Abstract Classes and interfaces
        • 3.3.1 Talk about your understanding of abstract classes and interfaces
          • Running results:
        • 3.3.2 Differences between Abstract Classes and Interfaces (Important)
      • 3.4 Talk about several inner classes and why they are used
        • 3.4.1 Several inner classes
        • 3.4.2 Why inner Classes

Java object oriented

1. Classes and objects

1.1 What is Process Orientation? What is object oriented?

Process oriented — step oriented

  • Process oriented is to analyze the steps needed to achieve the requirements, through functions (methods) step by step to achieve these steps, and then call

Object-oriented – Behavioral (relatively abstract concept, can be understood with the following example)

  • Object orientation is to divide the whole requirements according to characteristics and functions, and encapsulate these common parts into classes (objects are created after class instantiation). The object is not created to complete a certain step, but to describe the behavior of something in the steps of solving problems

1.1.1 Can you give an example of your understanding of process orientation and object orientation

For example, let’s design a pool game (skip the kick off and consider only the middle).

A: Process-oriented thinking:

This requirement is completed by implementing the following steps step by step through functions. (Just to demonstrate the concept, not to delve into the logic).

① Palyer1 hit the ball — ② to achieve the screen hit effect — ③ to judge whether the ball is scored and effective — ④ Palyer2 hit the ball

⑤ To achieve the screen hitting effect — ⑥ to judge whether the goal is scored and effective — ⑦ to return to step 1 — ⑧ output game results

B: Object-oriented thinking:

After observation, we can see that there are many commonalities in the above process, so we gather all these commonalities into a general structure

  1. Player system: includes Palyer1 and Palyer2

  2. Batting effect system: responsible for showing the user the picture of the game

  3. Rule system: judge whether there is a foul, win or lose, etc

We will tedious steps, through behavior, function, modular, which is object-oriented, we can even use the program, respectively, to quickly achieve 8 ball and snooker of different games (only need to modify the rules, map and ball color, player system, hitting effect system are consistent)

1.1.2 Advantages and disadvantages of procedural and object orientation

A: Process oriented

Advantages: Performance is superior to object-oriented because classes need to be instantiated at call time, which is too expensive.

Disadvantages: not easy to maintain, reuse, expansion

Purpose: microcontroller, embedded development, Linux/Unix and other high performance requirements

B: Object-oriented

Advantages: easy to maintain, easy to reuse, easy to expand, because of the characteristics of object-oriented encapsulation, inheritance, polymorphism, can design a low coupling system, make the system more flexible, more easy to maintain

Disadvantages: Generally lower performance than process-oriented

Low coupling: simple understanding means that modules should be as independent as possible between modules, the relationship between them should be as simple as possible, and they should be independently completed into some sub-functions as far as possible, which avoids the problem of affecting the whole body at the same time. This part will be systematically sorted out and summarized after the end of object-oriented learning.

Conclusion: only through textbooks after the sample is unable to realize the existing problems in the process oriented, in a few small routines, process-oriented feeling will be more simple, but once facing larger projects, we need to write N functionally similar function, more and more functions, code quantity is more and more, you will know that it’s a nightmare.

Note: On the performance of the problem, here is only in a general sense, the specific performance of the pros and cons, need to be combined with specific procedures, environment, etc

1.2 Explain the relationship and understanding of classes, objects, member variables and member methods

Class: A collection of related properties and behaviors, an abstract concept.

Object: a concrete representation of such a thing, a concrete being.

Member variables: Attributes of things

Member methods: Behavior of things

So how do we understand these concepts?

A class is a description of individuals with common characteristics and similar behaviors.

For example, Xiao Li and Lao Zhang both have names, ages, height, weight and other attributes, and they can chat, exercise and other similar behaviors.

Due to the two people have the common place, so we put it of abstracting, defined as a class – human beings, and xiao li, Lao wang is the individual in the class (object), and the existence of an individual is the true specific light mentioned people, you only know which properties should be behavior, but some of you don’t know his specific attribute values, For example, you know that he is “human” so he should have a name and age, but you don’t know his name or how old he is. But xiao Li and Lao Wang these two concrete objects, can actually know Lao Wang this year 30 years old, height 175 equivalent.

The result is that a class is an abstraction of an object, and an object is a concrete instance of a class. Classes are abstract and do not take up memory, which is required to actually instantiate concrete objects based on the class.

1.3 What is the difference between a member variable and a local variable?

A: Different position in the class

  • Member variables: outside of a method in a class

  • Local variables: code blocks, in method definitions or on method declarations (method parameters)

B: Different locations in memory

  • Member variables: in the heap

  • Local variables: on the stack

C: Different life cycles

  • Member variables: They exist as the object is created and disappear as the object disappears

  • Local variables: exist as the method is called and disappear as the method is called

D: The initialization values are different

  • Member variable: has a default value (the constructor initializes its value)

  • Local variables: there are no default values. They must be defined, assigned, and then used

1.3.1 Why are local variables in the stack and not the heap

There is a problem, when we learned about memory allocation in Java, there was a sentence, “heap memory is used to hold objects and arrays created by new”. , in other words the object exists in the heap, and member variables exist in class, and the object is a kind of specific individuals, so the member variables also exists in the heap, so the question becomes, in the same way, is the methods and member variables also exist in the object, and local variables defined in the method, that is to say, not a local variable also exists in the heap? This is clearly different from our definition above

Explanation: A class can create n different object, when we are new to an object, the object entity, has the memory space allocated on the heap, as a result of the class member variables vary in different objects (for example, xiao li and wang’s name), all need their respective storage space, so the members of the class variables is stored as object in the heap, The method of a class is common to all objects, so when an object is created, the method does not appear, only the declaration, the local variable in the method is not created, only when the object uses the method will be pushed to the stack.

Add: Class variables (static variables) exist in the method area, local variables that reference types are declared on the stack, and stored in the heap

1.4 Access modifier public, private, protected, and no write (default)

Access permissions class package A subclass Other packages
public Square root Square root Square root Square root
protect Square root Square root Square root
default Square root Square root
private Square root
  • Public: public, accessible by all classes in the project.
  • Protected: protected, accessible by the class itself; Accessed by classes in the same package; Accessed by its subclasses (the same package and subclasses in different packages).
  • Default: the default, accessible by the class itself; Accessed by a class in the same package.
  • Private: Private, accessible only by the class itself.

What does the 1.5 class do when it is initialized?

public class Student {
    private String name = "BWH_Steven";
    private Integer age = 22;
    
    // is a no-argument construct, with two assignment statements to demonstrate the initialization order
    public Student (a){ 
        name = ",";
        age = 30; }}public class Test {
    public static void main(String[] args) {
        Student stu = newStudent(); }}Copy the code

For example: Student stu = new Student(); It does the following in memory:

First load the student. class (compiled into bytecode files) file into memory, create space in stack memory for stu variables, create space in heap memory for Student objects instantiated from the Student class, initialize member variables of the Student object by default (e.g. Name = null, Age = 0), display initializes the member variables of the student object (for example, name = “BWH_Steven”, age = 22), and then assigns values to the member variables of the student object through the constructor (execute the assignment statement name = “ALvan” in the constructor, Age = 30) after the student object is initialized, assign the address of the object to the stu variable

1.6 What is the function of the static keyword?

A static method is a method without this. You cannot call a non-static method from inside a static method, and vice versa. And you can call static methods just from the class itself without creating any objects. This is actually the main purpose of static methods. Ideas for Java Programming, P86

Methods or variables decorated with the static keyword do not need to rely on the object to access them. Once the class is loaded, it can be accessed by the class name. That is, calls (methods/variables) can be made even if no object is created

Static can be used to modify class member methods, class member variables, and you can write static code blocks to optimize program performance.

1.6.1 What are Static methods

Static methods are usually called static methods. Static methods do not depend on object access, so there is no concept of this (this represents an object reference to the class), which is why all member variables and methods accessed by static methods must also be static

  • For example, if A non-static member B is called from static method A, it passesThe name of the class. AAccessing static method A, the object does not yet exist, and the non-static member B does not exist at all, so there is A problem. The same is true for calling a non-static method C, where you don’t know if a static variable is called

1.6.2 What are Static variables

A static variable is a class variable. It is stored in a static area of the method area. It is loaded as the class is loaded and it disappears.

1.6.3 What is a Static Code Block

A static code block is a code block declared in a class (not a method) with the static keyword and {}

static{... Content}Copy the code

Execution: Static code blocks run when the class is loaded, only once, and take precedence over various code blocks and constructors.

What it does: In general, static code blocks are needed if some code needs to be executed at project startup. For example, many configuration files and other resources that need to be loaded to start a project can be put into static code blocks.

1.6.3.1 Constructing Code Blocks (Supplementary)

Concept: code blocks declared in Java classes using {} (the difference with static blocks is that the static keyword is missing)

Execution: The construction block is called when the object is created, once each time the object is created, but takes precedence over the constructor execution.

Function: Similar to the function of the constructor, can initialize an object, and create only one object, the construction code block is executed once. Constructors, on the other hand, are not always executed for each object (multiple constructors are used to initialize objects with different parameters).

Because the constructor block is executed before each constructor is executed, the same code from multiple constructors can be placed here,

2. Three characteristics of object orientation

2.1 packaging

Concept of encapsulation

Encapsulation hides the attributes and implementation details of an object and provides only public access

  • In simple terms, I “lock up” data that I don’t want anyone to see, and internal details that no one else needs to know, leaving only a few entrances that connect to the outside world.

How do we “lock” our data?

  • We use permission modifiers such as public, private, and protected to set boundaries inside the class. These degrees of “locking” determine who can use what is defined next.

Benefits of encapsulation

Hiding implementation details and providing common access methods improves code reuse and security

Benefit 1: Hide implementation details and provide common access

What about hiding implementation details?

  • We’re encapsulating some functionality into a class, and the client programmer doesn’t need to know the logic of this method in the class, the class programmer just needs to give him an external interface, and the client programmer just needs to be able to call this method,

  • For example, when the dormitory is very hot in summer, we (users) only need to operate the remote control to use the air conditioner, without knowing how the air conditioner works inside

What about providing public access?

Let’s start with a standard case

public class Student {
	// Define a private member variable (private)
    private String name;
    private int age;
	
    // No arguments
    public Student(a) {
        super(a); }// with parameters
    public Student(String name, int age) {
        super(a);this.name = name;
        this.age = age;
    }
	
    // Set and get methods for member variables
    public void setName(String name) {
        this.name = name;
    }

    public String getName(a) {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge(a) {
        returnage; }}Copy the code
public class StudentTest {
    public static void main(String[] args) {
        // Create the student object s
        Student s = newStudent (a);// The object s calls the public methods setName() and setAge() in the class.
        // The set method assigns values to member variables
        s.setName("BWH_Steven");
        s.setAge(20);
        
        // The get method gets the member variableSystem.out.println(s.getName() + s.getAge()); }}Copy the code

We can see that in the above case, the member variables are private, and the get and set methods are public. In fact, the attributes that are private are the data that we want to lock, and the set and GET methods are the keys to unlock the lock

What is modified by private is that no one can access the elements except the type creator and the internal methods of the type, so we “lock” our data through private, and we can create objects to call public methods in a class. Therefore, the set and GET methods decorated by public are accessible to the outside world, and these two methods can directly access our private member variables, so the set and GET methods become the key to communicate with the outside world.

Benefit 2: Improved code reuse

Functionality is encapsulated into classes, and mechanisms (composition and inheritance) between base and derived classes improve code reuse

Benefit 3: Improved security (to be modified here)

As for the issue of safety, there is actually a debate. Let’s take a look at one saying:

public class Student {

    private String name;
    private int age;

    public Student(a) {
        super(a); }public Student(String name, int age) {
        super(a);this.name = name;
        this.age = age;
    }

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

    public String getName(a) {
        return name;
    }

    // Add validation to the setAge() method
    // Invalid data cannot be passed to a member variable
    public void setAge(int age) {
        if (age < 0 || age > 120) {
            System.out.println("Error");
        }else {
            this.age = age; }}public int getAge(a) {
        returnage; }}Copy the code
public class StudentTest {
    public static void main(String[] args) {
        Student s = new Student();
        System.out.println(s.getName() + s.getAge());
        
        // Wrong way!!
        s.name = "BWH_Steven";
        s.age = 20;
        System.out.println(s.getName() + s.getAge());
        
       	// The right way!!
        s.setName("BWH_Steven");
        s.setAge(20); }}Copy the code

There is no reason to use private to modify our member variable. If we change our member variable modifier to public, this means that the outside world can use the object directly to modify the member variable, which can cause some major problems

For example: the outside world through the object to assign a value to a member variable, you can assign some illegal data, which is obviously unreasonable. So you should evaluate the data before assigning it. StudenTest is a test class, and test classes typically just create objects and call methods, so this judgment should be defined in the Student class. Logical statements need to be used, and logical statements should be defined in the method. So the Student class provides a method to validate the data but if you don’t call a method to assign the value, the object name. Variables are assigned directly, so the logic in our method doesn’t work so we have to force my method to be used instead of calling member variables directly which is why we use private to decorate member variables!

Note: JavaBean classes, for example, typically don’t add any logic to set Get. It’s usually a simple assignment, and many frameworks and good projects use this canonical approach.

2.2 inheritance

Inheritance is to derive a new class from an existing class (for example, an animal class can be derived from dog and cat classes). The subclass inherits the characteristics and behaviors of the parent class so that the object (instance) of the subclass has the instance fields and methods of the parent class, or the subclass inherits methods from the parent class so that the subclass has the same behaviors of the parent class

Improved code reusability, improved code maintainability (with a small amount of modification to meet changing specific requirements), let class to class to generate a relationship, is the premise of polymorphism. But the downside is also significant: making classes more coupled, so that changes to one class affect other classes related to that class.

Features: Java supports only single inheritance, not multiple inheritance (C++ support), but Java supports multiple inheritance (inheritance system) image said: son inherits father, father inherits grandfather, son can inherit grandfather through father.

Note:

A: A subclass can only inherit all non-private members (member methods and member variables) of its parent class.

B: Subclasses cannot inherit the constructor of their parent class, but they can access the method using the super keyword

C: Do not inherit for partial functionality (multi-layer inheritance makes subclasses inherit redundant methods)

2.3 polymorphic

Polymorphism is the ability to have multiple different manifestations or forms of the same behavior. For example, black and white printers and color printers have different printing effects on the same behavior.

  • There is an inheritance (class)/implementation (interface) relationship between object types and reference types;

  • When a method is called in polymorphic mode, the first check is made to see if the method exists in the parent class. If not, a compilation error occurs. If so, call the subclass’s method of the same name.

  • If a subclass overrides a method of its parent class, it ends up executing the method overridden by the subclass; if it does not, it executes the method of its parent class.

3. The other

3.3 Abstract Classes and interfaces

3.3.1 Talk about your understanding of abstract classes and interfaces

Abstract class: we create an animal, and create animal object in this class, but when you mention animal, you don’t know what I mean animals, only to see the specific animals, you know what is this animal, so the animal itself is not a specific thing, but an abstract things. Only real cats and dogs are specific animals. Similarly, we can deduce that different animals have different behavior habits. Therefore, we should not give a specific embodiment in the animal class, but give a statement.

Interface: The common cat and dog case, cats and dogs they only provide some basic functions. But some are not animals themselves have, such as: cat drill fire ring, dog jump and other functions are trained in the later training, this extra function, Java provides interface representation.

3.3.1.1 Why must abstract classes override all abstract methods

“Cat” and “dog” are both entities of the class of “animal”. For example, animals both have the method of eat(), but dogs eat meat and cats eat fish. So the way each animal eats needs to be rewritten in subclasses, otherwise dogs and cats would be the same.

/ / Animal classes

public abstract class Animal {

    public void sleep(a) {
        System.out.println("I sleep on my stomach.");
    }
    public abstract void eat(a); 
}
Copy the code
/ / Dog class
public class Dog extends Animal {

    public Dog(a) {
        super(a); }@Override
    public void eat(a) {
        System.out.println("I implemented the superclass method, the dog eats meat."); }}Copy the code
/ / the Cat
public class Cat extends Animal{
    public Cat(a) {
        super(a); }@Override
    public void eat(a) {
        System.out.println("I implemented the superclass method, cats eat fish."); }}Copy the code
/ / test class
public class AnimalTest {
    public static void main(String[] args) {
        Animal a1 = new Dog();
        a1.sleep();
        a1.eat();
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        Animal a2 = newCat(); a2.sleep(); a2.eat(); }}Copy the code
Running results:
I lay sleeping I realized the parent class method, the dog meat -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- I lay sleeping I realized the parent class method, cats eat fishCopy the code

From the above example, we can see that Dog and Cat are two subclasses inherited from Animal. The methods of sleep() and eat() are the same and inherited from Animal, while the methods of eat() are defined as abstract methods in Animal class due to different characteristics, which are implemented in the subclasses respectively.

3.3.2 Differences between Abstract Classes and Interfaces (Important)

Let’s start with our actual design scenarios

Let’s start with a simple example:

Dogs have eat() and sleep() methods, and we define these abstractions through abstract classes and interfaces, respectively

// Defined by an abstract class
public abstract class Dog {
	public abstract void eat(a);
	public abstract void sleep(a);  
}
Copy the code
// By interface definition
public interface Dog {
    public abstract void eat(a);
    public abstract void sleep(a);
}
Copy the code

But how do we now increase this behavior if we need to give dogs a particular skill, DrillFireCircle()?

Think about:

  1. Write the ring of fire method to the abstract class along with the previous two methods, but this way, anyone inheriting this abstract class has the ring of fire skill, obviously not appropriate

  2. It is also not appropriate to write the drill fire ring method along with the previous two methods in the interface. When the drill fire ring function is required, it must implement the eat() and sleep() methods in the interface (overriding all methods in the interface)

So how to solve it? We can think about it, eat and sleep are dog itself should have a kind of behavior, and the fire drill this kind of behavior is trained by the day after tomorrow, can be an additional of dogs or extended, the two should not be in the same category, so we will consider the individual behavior, independent design an interface, It contains the DrillFireCircle() method, and Dog is designed as an abstract class that includes the eat() and sleep() methods.

A SpecialDog can inherit from the Dog class and implement the DrillFireCircle() interface

Here is the code:

// Define the interface with the drill fire ring method
public interface DrillFireCircle(a) {
    public abstract void drillFireCircle(a);
}

// Define the abstract dog class
public abstract class Dog {
    public abstract void eat(a);
    public abstract void sleep(a);
}
 
// Inherits the abstract class and implements the interface
class SpecialDog extends Dog implements drillFireCircle {
    public void eat(a) {
      / /...
    }
    public void sleep(a) {
      / /...
    }
    public void drillFireCircle(a) (a) {
      / /...}}Copy the code

Conclusion: Inheritance is a “no” relationship, whereas interface implementation is a “no” relationship. If a class inherits from an abstract class, the subclass must be the class of the abstract class, and the interface implementation is whether or not to have the relationship, such as whether the dog can drill through the ring of fire, can implement the interface, can not implement the interface.

3.4 Talk about several inner classes and why they are used

3.4.1 Several inner classes

Overview: A class defined inside another class is called an inner class.

For example, if the class Inner is defined in class Outer, it is called an Inner class.

class Outer {
    class Inner {}}Copy the code

Access rules: Inner classes can directly access members of outer classes, including private ones. For an external class to access an inner class member, it must create an object

Inner classes are classified as follows: A: member inner class, B: local inner class, C: static inner class, D: anonymous inner class

3.4.1.1 Member inner Classes

Member inner class – that is, a class that is located in the location of an external class member

Features: You can use all member variables and methods in an external class (private included)

A: Format:

class Outer {
    private int age = 20;
    // Member position
    class Inner {
        public void show(a) { System.out.println(age); }}}class Test {
    public static void main(String[] ages) {
        // Member inner classes are non-static demos
        Outer.Inner oi = new Outer().new Inner(a); oi.show(); }}Copy the code

B: When creating objects:

// Member inner classes are not static:External class name internal class name Object name =newExternal class name. new Inner class name ();// The inner class is static:External class name internal class name Object name =newOuter class name. Inner class name ();Copy the code

C: Member internal class common modifiers:

A: private

If our inner class does not want to be easily accessed by anyone, we can use private to decorate the inner class, so that we cannot access the inner class through the method that creates the object. To access the inner class, we only need to define a public method in the outer class and call it indirectly. The advantage of this is that we can add some judgment statements to the public method for data security purposes.

class Outer {
    private class Inner {
        public void show(a) {system.out.println (" password backup file "); }}public void method(a) {
    	if(you are the administrator){Inner I =new Inner();
    		i.show();
    	}else{system.out.println (" you don't have permission to access "); }}}Copy the code

So let’s write it a little bit more formally

class Outer {
    private class Inner {
        public void show(a) {system.out.println (" password backup file "); }}// Use getXxx() to get the inner class of the member.
    public Inner getInner(a) {
		return new Inner();
   	}
    
    public static void main(String[] args) {
    	Outer outer = newOuter(); Outer.Inner inner = outer.getInner(); inner.show(); }}Copy the code

B: the static

This static inner class is classified by position as a member inner class, but can also be called a static inner class, and is often called a nested inner class. The specific content will be explained in detail below.

D: Members of the inner class classic questions (fill in the blank)

Please fill in the parentheses after the three printlns so that the output is 25,20,18

class Outer {
	public int age = 18;	
	class Inner {
		public int age = 20;	
		public viod showAge(a) {
			int age  = 25;
			System.out.println(age);/ / 1
			System.out.println(this.age);/ / 2
			System.out.println(Outer.this.age);/ / 3}}}Copy the code

3.4.1.2 Local inner Classes

Local inner classes – classes defined in a method or scope

Features: The scope has changed and can only be used in its own methods and attributes

A format:

class Outer {
    public void method(a){
        class Inner {}}}Copy the code

B: When visiting:

// In a local location, you can create inner class objects through object calls and inner class methods
class Outer {
    private int age = 20;
    public void method(a) {
        final int age2 = 30;
        class Inner {
            public void show(a) {
           	    System.out.println(age);
                // Access the method variable age2 from an inner class, declaring the variable to be of final type.
                System.out.println(age2);
            }
        }
        
        Inner i = newInner(); i.show(); }}Copy the code

C: Why do local inner classes have to be final to access local variables?

Because local variables are called as the method is called and disappear after use, data in heap memory does not disappear immediately.

So, heap memory still uses that variable, and that variable is gone. To keep the value alive, add the final modifier.

The reason is that when we modify variables with final, the heap memory stores the value directly, not the variable name.

Age2 stores the constant 30 instead of age2.

3.4.1.3 Static Inner Classes

We know that static cannot be used to modify a class, but a member inner class can be treated as a member of an outer class, so we can use the static inner class.

Features: You cannot use non-static member variables and member methods of an external class

Explanation: Non-static inner classes are compiled to save a reference to the outer class by default, while static classes do not.

Static inner class objects can be created even if there is no external class object, whereas non-static members of the external class must depend on the call of the object. Static members can be called directly from the class and do not depend on the object of the external class, so static inner classes can only access static external properties and methods.

class Outter {
    int age = 10;
    static age2 = 20;
    public Outter(a) {}static class Inner {
        public method(a) {
            System.out.println(age);/ / error
            System.out.println(age2);/ / right}}}public class Test {
    public static void main(String[] args)  {
        Outter.Inner inner = newOutter.Inner(); inner.method(); }}Copy the code

3.4.1.4 Anonymous Inner Classes

A class without a name is a shorthand for an inner class

A format:

newClass name or interface name () {override method (); }Copy the code

Essence: An anonymous object that inherits the class or subclasses that implement the interface

In this case, you can simply use new Inner() {}.show(); The reason is equal to subclass object.show ();

interface Inter {
	public abstract void show(a);
}

class Outer {
    public void method(a){
        new Inner() {
            public void show(a) {
                System.out.println("HelloWorld"); } }.show(); }}class Test {
	public static void main(String[] args)  {
    	Outer o = newOuter(); o.method(); }}Copy the code

What if there are multiple methods in an anonymous inner class?

Inter i = new Inner() {  // polymorphic, because new Inner(){} represents a subclass of the interface
	public void show(a) {
		System.out.println("HelloWorld"); }};Copy the code

B: Use of anonymous inner classes in development

When we’re developing, we’ll see abstract classes, or interfaces, as parameters.

In this case, all you really need is a subclass object.

If this method is called only once, we can use the formatting simplification of anonymous inner classes.

3.4.2 Why inner Classes

3.4.2.1 encapsulation

As a class writer, we obviously need to limit the access to the user of this class, and we need to hide operations that we don’t want others to see.

If our inner class does not want to be easily accessed by anyone, we can use private to decorate the inner class, so that we cannot access the inner class through the method that creates the object. To access the inner class, we only need to define a public method in the outer class and call it indirectly.

public interface Demo {
    void show(a);
}
Copy the code
class Outer {
    private class test implements Demo {
        public void show(a) {
            System.out.println("Password Backup file"); }}public Demo getInner(a) {
        return newtest(); }}Copy the code

Let’s look at the test

    public static void main(String[] args) {
    	Outer outer = new Outer();
        Demo d = outer.getInner();
        i.show();
    }

// Run the resultPassword backup fileCopy the code

One of the benefits of this is that we can add some judgment statements to the public method for data security purposes.

Second, all we see is the getInner() method, which returns an instance of the Demo interface, while the name of our real inner class is hidden

3.4.2.1 Implementing Multiple Inheritance

Before we learn to know, Java is not can realize multiple inheritance, one can only inherit a class, we study the interface, the interface can be used to implement multiple inheritance was mentioned, that is, a interface has multiple implementations, but it also has some disadvantages, that is, once implemented in an interface must implement all the methods, This can sometimes be a bit cumbersome, but using inner classes is a good way to solve these problems

public class Demo1 {
    public String name(a) {
        return "BWH_Steven"; }}Copy the code
public class Demo2 {
    public String email(a) {
        return "[email protected]"; }}Copy the code
public class MyDemo {

    private class test1 extends Demo1 {
        public String name(a) {
            return super.name(); }}private class test2 extends Demo2  {
        public String email(a) {
            return super.email(); }}public String name(a) {
        return new test1().name();
    }

    public String email(a) {
        return new test2().email();
    }

    public static void main(String args[]) {
        MyDemo md = new MyDemo();
        System.out.println("My name :" + md.name());
        System.out.println("My email :"+ md.email()); }}Copy the code

We write two classes Demo1 and Demo2 to be inherited, and write two inner classes in MyDemo. Test1 and test2 inherit from Demo1 and Demo2 respectively, so that MyDemo indirectly implements multiple inheritance

3.4.2.3 Implement callback functionality with anonymous inner classes

In Java, you write an interface, you implement that interface, you pass an object of that interface as a parameter to another program method, and then you call your method through that interface. Anonymous inner classes do a pretty good job of representing this callback function

public interface Demo {
    void demoMethod(a);
}
Copy the code
public class MyDemo{
    public test(Demo demo){
    	System.out.println("test method");
    }
    
    public static void main(String[] args) {
        MyDemo md = new MyDemo();
        // Here we pass the interface object as an argument to the test method using an anonymous inner class
        md.test(new Demo){
            public void demoMethod(a){
                System.out.println("Concrete implementation interface")}}}}Copy the code

3.4.2.4 Solving the problem that the Inheritance and implementation interface has the same name Method

public interface Demo {
    void test(a);
}
Copy the code
public class MyDemo {

    public void test(a) {
        System.out.println("Test method of parent class"); }}Copy the code
public class DemoTest extends MyDemo implements Demo {
    public void test(a) {}}Copy the code

So I’m a little confused, how do we tell if this method is interface or inheritance, so we use inner class to solve this problem

public class DemoTest extends MyDemo {

    private class inner implements Demo {
        public void test(a) {
            System.out.println("Test method for interface"); }}public Demo getIn(a) {
        return new inner();
    }
    
    
    public static void main(String[] args) {
        // Call the test() method from the interface
        DemoTest dt = new DemoTest();
        Demo d = dt.getIn();
        d.test();
        
        // Call the inherited test() methoddt.test(); }}// Run the resultThe test method of the interface's test method parent classCopy the code