The modifier

In a class, a member variable that uses a static modifier is a static variable, and a non-static variable. Static variables are classes that “can” be accessed using the class name. Non-static variables are objects that “must” be accessed using objects.

1	public class Student{
2	private static int age;
3	private double score;
4	
5	public static void main(String[] args) {
6	Student s = new Student();
7	// Using the class name to access static members is recommended
8	System.out.println(Student.age);
9	System.out.println(s.age);
10	
11	System.out.println(s.score);
12	}
13	}
Copy the code

A static variable is only one in memory for a class and can be shared by all instances of the class. Instance variables have a copy for each instance of the class and do not affect each other.

public class Student{
private static int count;
private int num;
public Student(a) {

count++;
num++;
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Student s4 = new Student();
// Since it is still in a class, private attributes can be accessed directlySystem.out.println(s1.num); System.out.println(s2.num); System.out.println(s3.num); System.out.println(s4.num); System.out.println(Student.count); System.out.println(s1.count); System.out.println(s2.count); System.out.println(s3.count); System.out.println(s4.count); }}Copy the code

Static variables are allocated memory during class loading, and instance variables are allocated memory when the object is created, so static variables can be accessed using the class name instead of the object. The difference between static and non-static methods

Static methods belong to classes and can be called using the class name. Non-static methods belong to objects and must be called using the object.

Static methods “cannot” access non-static variables and methods in a class, but “can” access static variables and methods in a class. Note: This and super are non-static variables in a class.

public class Student{
private static int count;
private int num;
public void run(a){}
public static void go(a){}

public static void test(a){
// The compiler passes
System.out.println(count);
go();

// Compile errorSystem.out.println(num); run(); }}Copy the code

Non-static methods can directly access non-static variables and methods in a class, as well as static variables and methods in a class

public class Student{
private static int count;
private int num;
public void run(a){}
public static void go(a){}

public void test(a){
// The compiler passes
System.out.println(count);
go();

// The compiler passesSystem.out.println(num); run(); }}Copy the code

Consider: Why can’t static and non-static methods directly access each other? Loading order problem! Static methods of a parent class can be inherited by subclasses, but cannot be overridden by them.

public class Person {
public static void method(a) {}}// Compile error
public class Student extends Person {
public void method(a){}} Example:public class Person {
public static void test(a) {
System.out.println("Person"); }}// Compile passes, but not overwrite
public class Student extends Person {
public static void test(a){
System.out.println("Student");
}
}

main:
Perosn p = new Student();
p.test();/ / output Person
p = new Person();
p.test();/ / output Perosn
Copy the code

Unlike nonstatic methods, a nonstatic method of a parent class cannot be overridden by a subclass as a static method.

public class Person {
public void test(a) {
System.out.println("Person"); }}// Compile error
public class Student extends Person {
public static void test(a){
System.out.println("Student"); }}Copy the code

3, Code blocks and static code blocks

public class Person {{// Code block (anonymous code block)
}

static{
// Static code block}}Copy the code

Anonymous code block and static code block execution because there is no name, the program cannot actively call these code blocks. Anonymous code blocks are executed automatically when the object is created and before the constructor executes. Anonymous code blocks are automatically executed each time an object is created. Static code blocks are executed automatically after the class is loaded and only once. Note: Each class is loaded the first time it is used, and usually only once.

public class Person {
{
System.out.println(Anonymous code block);
}

static{
System.out.println("Static code block");
}

public Person(a){
System.out.println("Constructor");
}
}
main:
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();

/ / output
Copy the code

Anonymous code blocks are used to initialize the value of an object’s member variables, but because the constructor can also do this, anonymous code blocks are not used much. Static code blocks are used to initialize assignments to static member variables in a class. Such as:

public class Person {
public static String name;
static{
name = "tom";
}
public Person(a){
name = "zs";
}
}

main:
System.out.println(Person.name);//tom
Copy the code

Note: Assigning a value to a static variable in a constructor does not guarantee that the assignment will succeed because the constructor is pointed at the time the object is created, but a static variable can be accessed using the class name without creating the object

Student s = new Student();

1. Class load and initialize static attribute 2. Execute static code block 3. Allocate memory space and initialize non-static properties (assign default values,0/false/ NULL) 4. Call Student’s parent class constructor 5. Display assignments to attributes in Student (if any) 6. Note: Display assignments of non-static attributes in a subclass are done after the parent constructor is executed and before the anonymous code block in the subclass is executed

1public class Person{
2private String name = "zs";
3public Person(a) {
4System.out.println("Person constructor");
5print();
6	}
7	public void print(a){
System.out.println("Person print method: name ="+name); }}public class Student extends Person{
private String name = "tom";
{
System.out.println(Student Anonymous code block);
}

static{
System.out.println(Student static code block);
}
public Student(a){
System.out.println("Student constructor");
}
public void print(a){
System.out.println("Student print method: name ="+name);
}
public static void main(String[] args) {
newStudent(); }}/ / output:Student static block Person constructor Student print method: name =nullStudent anonymous code block Student constructor Student s =newStudent(); The Student class has already been classloaded1.Allocate memory while initializing non-static properties (assign default values,0/false/null)
2.Invoke Student's parent class constructor3.Display assignments to attributes in Student (if any)4.Execute anonymous code blocks5.Execution constructor6.Return memory addressCopy the code

Static import is the static import of Java packages. Replacing import static with import static is a new feature in JDK1.5. Import static methods from this class. Benefits: The advantage of this approach is that it can simplify operations such as printing system.out.println (…). ; Write it to a static method: print(…) Print (…) That’s it. However, this method is recommended when there are many repeated calls. If there are only one or two calls, it is better to write them directly

import static java.lang.Math.random;
import static java.lang.Math.PI;

public class Test {
public static void main(String[] args) {
Math.random() is called beforeSystem.out.println(random()); System.out.println(PI); }}Copy the code

Unde final modified classes are not generatedand have no subclasses. For example, there is no way to write a class that extends String and then extends String because the API is de final already defined by the String class. We can also define final modified classes:

public final class Action{}// Compile error
public class Go extends Action{}Copy the code

Methods with final modifications can be inherited but cannot be overridden by subclasses. For example, each class is a subclass of Object and inherits many methods from Object. In the subclass, toString method, equals method, etc. can be overridden, but getClass method wait method cannot be overridden, because these methods are fianl modified. We can also define the method of final modification:

public class Person{
public final void print(a){}}// Compile error
public class Student extends Person{
public void print(a){}}Copy the code

Constants are final modified variables that can only be assigned a value once. In fact, variables with final modifications are constants because the values do not change. 【 modify local variables 】

1public class Person{2public void print(final int a){
3// An error was reported during compilation. The value cannot be assigned again because it was already assigned when the parameter was passed
4	a = 1; }}public class Person{
public void print(a){
final int a;
a = 1;
// Compile error, cannot assign value again
a = 2; }}Copy the code

Modifying member variables – non-static member variables

public class Person{ private final inta; } There is only one chance to assign to this variable a at the same location as the declaration in the anonymous code blockCopy the code

Member variables – Static member variables

public class Person{
private static final inta; } There is only one chance to assign to the position of the variable a: in the static code block where the assignment is declared at the same timeCopy the code

【 Modify reference variables 】

main:
final Student s = new Student();
// The compiler passes
s.setName("tom");
s.setName("zs");

// The memory address referenced by s cannot be modified
s = new Student();
Copy the code

The abstract modifier can be used to modify a method or a class. If you modify a method, it is an abstract method. If you modify a class, then that class is abstract. Abstract classes may not have abstract methods, but classes with abstract methods must be declared as abstract classes. 2, grammar,

public abstract class Action{
public abstract void doSomething(a);
}


public void doSomething(a){... }Copy the code

For this normal method: “public void doSomething()” this part is the declaration of the method “{… }” this part is the implementation of the method, and if there’s nothing in the curly braces, it’s called the empty implementation of the method that declared the class and added the abstract modifier to it, removed the big number of the method, and ended with a semicolon, that’s the abstract method. Abstract classes. You cannot use the new keyword to create objects, which are inherited by subclasses. Abstract methods, only method declaration, no method implementation, it is used to subclass implementation. Note: When a subclass inherits from an abstract class, it needs to implement an abstract method that is not implemented in the abstract class. Otherwise, the subclass must also be declared as an abstract class.

public abstract class Action{
public abstract void doSomething(a);
}

main:
// An abstract class cannot create a new object
Action a = new Action();

// Subclasses inherit abstract classes
public class Eat extends Action{
// Implement abstract methods that are not implemented in the parent class
public void doSomething(a){
//code
}
}

main:
Action a = new Eat();
a.doSomething();
Copy the code

Note: If a subclass inherits an abstract class, it must implement an abstract method that the abstract class does not implement, or else it must be declared as an abstract class. 1: Abstract classes can’t create new objects. Is there a constructor in an abstract class?

Abstract classes cannot be instantiated. The purpose of an abstract class is to implement commonalities in polymorphism. The constructor of an abstract class is called when a subclass instantiates, so it is also used to implement commonalities in polymorphism.

Thought 2: The meaning of Abstract classes and methods (Why write Abstract classes and methods)

Let’s say you play a game. If you want to create a role, creating classes and methods repeatedly can be tedious and cumbersome. Create an abstract class. To create roles, you can directly inherit fields and methods from an abstract class, which in turn has abstract methods. If a character has many classes, and each class has many skills, it would be awkward to use them in sequence. You can save a lot of code by defining abstract methods and then overriding the calls as needed. In short, abstract classes and methods act as a framework. It is very convenient to call and rewrite abstract methods later for the sake of program extensibility. Overriding an abstract method can fulfill the requirement of having the same name but not the same purpose.

interface

1, the nature of the interface common class: only concrete implementation abstract class: concrete implementation and specification (abstract method) have! Interface: Specification only! Why do you need an interface? The difference between an interface and an abstract class? An interface is an “abstract class” that is more “abstract” than an “abstract class” and can impose more formal constraints on subclasses. Fully and professionally implemented: separation of specification and concrete implementation. Abstract classes also provide some concrete implementation. Interfaces provide no implementation, and all methods in interfaces are abstract methods. Interfaces are fully canonical, specifying common method specifications for a set of classes. From an implementer’s point of view, an interface defines a service that can be provided externally. From the perspective of the caller of the interface, the interface defines which services the implementer can provide. Interface is the standard and specification of communication between two modules. If you can define the interface between the modules between the systems you want to design, it is equivalent to complete the design outline of the system, and the rest is the concrete implementation of building blocks. After work, we often use the idea of “interface oriented” to design the system when doing the system. An interface is a specification. It defines a set of rules that reflect the real world’s “if you are… Must be able to…” Thoughts. If you are an angel, you must be able to fly. If you’re a car, you have to run. If you are good, you must kill the bad. If you are bad, you must bully the good. The essence of an interface is a contract, as is the law among us. It’s made and everybody sticks to it. At its core, OO is the abstraction of objects, and nowhere is this more evident than in interfaces. The reason why we talk about design patterns is only for languages that have the ability to abstract (c++, Java, c#, etc.) is that design patterns are really about how to abstract properly. Abstract classes are also classes, except that they can write abstract methods and cannot directly new objects, the other and ordinary classes are no different. Interfaces are of a different type, and classes are fundamentally different, so you can’t use class standards to measure interfaces. The keyword for declaring a class is class, and the keyword for declaring an interface is interface. Abstract classes are designed to be inherited; classes in Java are single-inherited. Class A extends from abstract class B, so objects of class A are of type B. You can use polymorphic references to A parent class that point to any subclass of that parent class. Class A implements interfaces B, C, D, E… , then the object of the class A is B, C, D, E, such as type, can using polymorphic reference an interface, can point to any implementation class object (note: this interface is the keyword implements 3, the interface methods are abstract methods in the interface can not write any method, but if the writing methods, this method must be abstract methods

public interface Action{
public abstract void run(a);

// The default is public abstract
void test(a);
public void go(a);
}
Copy the code

4. The variables in the interface are all static constants. No properties can be written in the interface, but if a property is written, the property must be a static constant of a public static final modification. Note: You can access its properties directly using the interface name. Public static; static; public static;

public interface Action{
public static final String NAME = "tom";
Public static final int AGE = 20;
}
main: System.out.println(Action.NAME); System.out.println(Action.AGE);
Copy the code

5. A class can implement multiple interfaces

Public class Student implements A,B,C,D{//Student implements A,B,C,D} main: A s1 = new Student(); B s2 = new Student(); C s3 = new Student(); D s4 = new Student();

Note: S1 can only call the methods declared in interface A and Object, S2 can only call the methods declared in interface B and Object, S3 can only call the methods declared in interface C and Object, S4 can only call the methods declared in interface D and Object For example: test() in interface A and run() in interface B

A s1 = new Student();
s1.test();

B s2 = new Student();
s2.run();

if(s1 instanceof B){
((B)s1).run();
}
Copy the code

An interface can inherit from multiple parent interfaces

public interface A{
public void testA(a);
}

public interface B{
public void testB(a);
}

// interface C inherits methods from interface A and B
public interface C extends A.B{
public void testC(a);
}

//Student implements A, B, and C interfaces
//Student's object is of type A, type B, type C
public class Student implements C{
public viod testA(a){}
public viod testB(a){}
public viod testC(a){}
}

main:
C o = new Student();
System.out.println(o instanceof A);//true
System.out.println(o instanceof B);//true
System.out.println(o instanceof C);//true
System.out.println(o instanceof Student);//true
System.out.println(o instanceof Object);//true
System.out.println(o instanceof Teacher);//false

// Compile error
System.out.println(o instanceof String);
Copy the code

Note: the System. The out. Println instanceof X (o);

If o is a variable declared by the interface type, the code will compile as long as X is not a final modified class, depending on whether the actual type of the object o points to is a subclass or implementation of X.

Note: A reference to an object may implement any interface. The main function of the interface is to achieve uniform access, that is, when creating an object with the interface to create [interface name] [object name] = new [implementation of the interface] so that you can use which class of the object can be new which object, do not need to change the original code. If we have a function() method in both classes, if I’m using an interface, then I’ll call new a(); This is called unified access, because the class that you implement this interface has the same method name but different implementation content. Summary: 1. Member variables in Java interfaces are public,static, and final by default and must be instantiated as constants in the interface (capital letters, words separated by “_”). By default, methods in Java interfaces are public and abstract, and no method body can be instantiated. 3. Java interfaces can only contain member variables of public,static, and final types and member methods of public and Abstract types An interface cannot implement another interface, but it can inherit multiple other interfaces. Java interfaces must implement abstract methods through classes When a class implements a Java interface, it must implement all the abstract methods in the interface. Otherwise, the class must be declared as an abstract class. A class can only inherit from a direct parent class, but can implement multiple interfaces, indirectly implementing multiple inheritance.

> interface SwimInterface{
void swim(a);
}
class Fish{
int fins=4;
}
class Duck {
int leg=2;
void egg(a){};
}

class Goldfish extends Fish implements SwimInterface {
@Override
public void swim(a) {
System.out.println("Goldfish can swim "); }}class SmallDuck extends Duck implements SwimInterface {
public void egg(a){
System.out.println("SmallDuck can lay eggs ");
}
@Override
public void swim(a) {
System.out.println("SmallDuck can swim "); }}public class InterfaceDemo {
public static void main(String[] args) {
Goldfish goldfish=new Goldfish();
goldfish.swim();

SmallDuck smallDuck= newSmallDuck(); smallDuck.swim(); smallDuck.egg(); }}Copy the code

The inner class

In the last section, we learned about interfaces. Interfaces are often encountered in future work, so we must review them more often. Next, inner classes. Most of the time we don’t need to use it many times to create the object of the class, only once at a time, and then we can use the inner class. An inner class is defined inside A class. For example, if class B is defined in class A, then class B is called an inner class relative to class A, and class A relative to class B is an outer class. Instead of writing two parallel classes in a Java source file, inner classes define another class inside a class. We can call outer classes outer classes, and classes written inside them inner classes. Internal classes are divided into four types: 1. Member internal class 2. Static internal class 3. Anonymous inner class 2, member inner class (instance inner class, non-static inner class)

// A class B is declared inside A member variable, so it is called A member inner class
public class Outer {
private int id;
public void out(a){
System.out.println("This is an external class method.");
}

class Inner{
public void in(a){
System.out.println("This is an inner class method."); }}}Copy the code

[Instantiate inner class] Instantiate inner class, first need to instantiate the outer class, through the outer class to call the inner class

public class Outer {
private int id;
public void out(a){
System.out.println("This is an external class method.");
}

class Inner{
public void in(a){
System.out.println("This is an inner class method."); }}}public class Test{
public static void main(String[] args) {
Instantiating a member inner class is a two-step process
// instantiate the external class
Outer outObject = new Outer();
// call the inner class from the outer class
Outer.Inner inObject = outObject.new Inner(a);
// Test to call a method in the inner class
inObject.in();// Print: This is the inner class method
}}
Copy the code

Analysis: If you want to use a method or attribute in a class, you must first have an object of that class. Similarly, if a class is inside another class, you must first have an instance object of the outer class and then use the inner class through that object. What can member inner classes do?

  1. Access all attributes of the external class (including private member variables, methods)
public class Outer {
private int id;
public void out(a){
System.out.println("This is an external class method.");
}

class Inner{
public void in(a){
System.out.println("This is an inner class method.");
}

// The inner class accesses the private member variables of the outer class
public void useId(a){
System.out.println(id+3); . }// The inner class accesses the outer class's methods
public void useOut(a){ out(); }}}public class Test{
public static void main(String[] args) {
Instantiating a member inner class is a two-step process
// instantiate the external class
Outer outObject = new Outer();
// call the inner class from the outer class
Outer.Inner inObject = outObject.new Inner(a);
/ / test
inObject.useId();// print 3, because id initializes to 0,0 +3 is 3, where the inner class is usedThe private member variable ID of the external class. inObject.useOut();// Print: This is the external class method
}
}`
Copy the code

1. If the name of the variable in the inner class is the same as the name of the member variable in the outer class, access the outer class property by creating the “.” property of the outer class object, through this. Property accesses inner class member properties

1public class Outer {
2private int id;// Initialize 0 by default
3public void out(a){
4System.out.println("This is an external class method.");
5	}
Copy the code

1. To access the contents of an inner class, you must instantiate the inner class through an external class object. Outer. This provides access to all properties and methods of the Outer class. When the Outer class is instantiated, the Outer class passes a reference to the inner class, so that the inner class can call the Outer class properties and methods with Outer. But when the inner class has an attribute or method name that is the same as the Outer class, you need to explicitly call Outer. 【 WRITE a small example 】

public class MemberInnerClassTest {
private String name;
private static int age;

public void run(a){}

public static void go(a){}

public class MemberInnerClass{
private String name;

// Inner classes access outer classes
public void test(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(MemberInnerClassTest.this.name);
System.out.println(MemberInnerClassTest.age);
MemberInnerClassTest.this.run(); MemberInnerClassTest.go(); }}// The external class accesses the member inner class
// The objects of the member inner class depend on the existence of the objects of the outer class
public void test(a){
//MemberInnerClass mic = MemberInnerClassTest.this.new
MemberInnerClass();
//MemberInnerClass mic = this.new MemberInnerClass();
MemberInnerClass mic = new MemberInnerClass();
mic.name = "tom";
mic.test("hua");

}

public static void main(String[] args) {
//MemberInnerClass mic = new MemberInnerClass(); This is not going to work. This is going to moveThe state.// Create an external class object before using it
MemberInnerClassTest out = new MemberInnerClassTest();
MemberInnerClass mic = out.new MemberInnerClass(a);
// If the inner class is private, it cannot be accessed, only the inner method can be called
mic.name="jik";
mic.test("kkk"); }}Copy the code

An inner class that uses your static modifier is called a static inner class. Static is used to modify variables and methods. Classes are not normally modified, but inner classes can be modified static. Static modifiers: all instances of a class share a static variable. Static methods can only access properties or methods that have been modified static. Non-static methods can access methods or properties that have been modified static. Static does not modify local variables. Static is used to modify member variables and methods. Write an example, can show you:

public class StaticInnerClassTest {
private String name;
private static int age;

public void run(a){}

public static void go(a){}

// The external class accesses the static inner class
public void test(a){
StaticInnerClass sic = new StaticInnerClass(); // Static inner classes do not require dependenciesExternal class, so nothis
sic.name = "tom";
sic.test1("jack");

StaticInnerClass.age=10;
StaticInnerClass.test2("xixi");

}

private static class StaticInnerClass{
private String name;
private static int age;
public void test1(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(StaticInnerClass.age);

System.out.println(StaticInnerClassTest.age);
//System.out.println(StaticInnerClassTest.this.name); Static classes cannot be accessedAsk the non-static attribute Staticinnerclasstest.go ();//StaticInnerClassTest.this.run(); Static classes cannot access non-static methods
}
public static void test2(String name){
// Access only static properties and methods of its own and external classes
System.out.println(name);
//System.out.println(this.name); A static method cannot even have a non-static property of its own classAccess to the System. The out. Println (StaticInnerClass. Age); System.out.println(StaticInnerClassTest.age);//System.out.println(StaticInnerClassTest.this.name); Static methods cannotAccess the non-static property StaticInnerclasstest.go ();//StaticInnerClassTest.this.run(); Static methods cannot access non-static methods}}}Copy the code

The inner class can call the methods and properties of the outer class. The static inner class can call the methods and properties of the outer class. The static inner class has no reference to the outer class object. Unless the method or property in the external class is also static. This brings us back to the static keyword. A static inner class can be instantiated directly by an external class without using an external class object

Outer.Inner inner = new Outer.Inner();
Copy the code

Static inner classes can declare static methods and static variables, but non-static inner classes cannot declare static methods and static variables

A local inner class is a class local inner class declared inside a method that can access the member variables of the external class and method local inner class. If you want to access the local variables in the method of the inner class, the local variables must be final modification

public class Outer { private int id;
In method01, there is an Inner class. This Inner class is called a local Inner class
public void method01(a){class Inner{ public void in(a){
System.out.println("This is a local inner class."); }}}Copy the code

The general function of local inner classes is similar to that summarized in member inner classes, but with two caveats: 1. In a local inner class, if a local variable is to be accessed, final modification of the local variable is to be used why is this used? final modified variables: Is a constant, will put in constant pool, reverse thinking to this problem, if not practical fi nal decorate, authorities department class is instantiated, methods play stack, local variables as follow to disappear, want to at this time for local inner class object to call the local variable quantity, will be an error, because of the local variable is gone, when the local variables with the fanal modification, It will be added to the constant pool, even if the method is stacked, the local variable will remain in the constant pool, the local inner class is just enough to call. Therefore, local inner classes that want to call local variables need to be modified with final. If they are not used, the compilation fails.

public class Outer {
private int id;
public void method01(a){
final int cid = 3;	// this is the local variable cid. To be used by a local inner class, change to
finalAnd assign if not usedfinalModifier, an error will be reportedclass Inner{
// The first method of the inner class
public void in(a){
System.out.println("This is a local inner class.");
}
// a method in an inner class that uses the local variable CID
public void useCid(a){ System.out.println(cid); }}}}Copy the code
  1. A local inner class cannot be instantiated directly from an external class object. Instead, it instantiates itself in a method and then calls methods in its own class through the inner class object. See the following example to see how to use it.
public class Outer {
private int id;

public void out(a){
System.out.println("External class method");
}
public void method01(a){
class Inner{
public void in(a){
System.out.println("This is a local inner class."); }}// The key here is to create an inner class instance in a Method01 method, call the inner class method, wait for the outer class to call method01, and execute the inner class method.
		Inner In = newInner(); In.in(); }}Copy the code

Use of local inner class need to pay attention to the above: 1. In local inner class, if you want to access the local variable, then the local variable should be with final modification 2. How to call local inner class methods.

public class LocalInnerClassTest {
private String name;
private static int age;

public void run(a){}

public static void go(a){}

// Local inner classes are defined in methods
public void test(a){
final String myname="";
class LocalInnerClass{
private String name;
// private static int age; Static properties cannot be defined

public void test(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(myname);
System.out.println(LocalInnerClassTest.this.name);

LocalInnerClassTest.this.run(); LocalInnerClassTest.go(); }}// A local inner class can only be used in its own method, because a local inner class is equivalent to a local variableArrived. LocalInnerClass lic =new LocalInnerClass();
lic.name="tom";
lic.test("test"); }}Copy the code

5, anonymous inner class in these four inner classes, the future work may encounter the most is anonymous inner class, so the anonymous inner class is the most commonly used inner class. What are anonymous objects? If an Object is only used once, then we need new Object().method(). You don’t need to store the instance in the type variable. This is the anonymous object.

public class Test {
public static void main(String[] args) {
// Assign the new Apple instance to the Apple variable and save it, but we only need to use it once, we can say Apple = new Apple();
apple.eat();
// This is called the use of anonymous objects and does not store instances in variables. new Apple().eat();}}class Apple{
public void eat(a){ System.out.println("I'm going to get eaten.");
}
Copy the code

Anonymous inner classes are similar to anonymous objects: Anonymous objects: I only need to use them once, so I don’t have to declare a variable of that type to hold the object. Anonymous inner classes: I only need to use it once, so instead of defining an inner class in my class, I’m going to wait until I need to use it, and I’m going to implement this inner class on the fly, because I don’t use it a lot, maybe just this once, so it’s easier to write the inner class that way. Otherwise, write out the entire implementation of an inner class, and then call it once, and then leave it there forever. There’s no need to do that. 1. An anonymous inner class needs to be created from another class or interface. If it is based on a class, the anonymous inner class is created by default as a subclass of that class. 2. The declaration of the anonymous inner class must be the same as the creation of the object when using the new keyword, and can be used repeatedly later because there is no name. [Example] A is A class (common or abstract) that creates an anonymous inner class object based on class A

main:

A a = new A(){
// Implement the abstract method in A
// Or override the normal method in A}; Note: inside the braces is the code for the inner classnewIts object is created and cannot be used repeatedly because it has no name. For example: B is an interface, which creates an anonymous inner class object B B =new B(){
// Implement abstract methods in B
};
Copy the code

1. An anonymous inner class cannot be specified to inherit or implement any other class or interface than the one it depends on, nor can it be inherited by any other class because it has no name. 2. In anonymous interiors, we cannot write out its constructor because it has no name. In anonymous interiors, there are generally no more unique methods written than those above, because they cannot be called directly from the outside. (Indirection is called to)

public interface Work{
void doWork(a);
}
public class AnonymousOutterClass{
private String name;
private static int age;
public void say(a){}
public static void go(a){}

public void test(a){
final int i = 90;

Work w = new Work(){
public void doWork(a){
System.out.println(AnonymousOutterClass.this.name);
System.out.println(AnonymousOutterClass.age);
AnonymousOutterClass.this.say(); AnonymousOutterClass.go(); System.out.println(i); }}; w.doWork(); }}Copy the code

We can see the difference between implementing a method in an interface without an anonymous inner class and using an anonymous inner class.

public class Test {
public static void main(String[] args) {
// If we need to use the methods in the interface, we need to do 3 steps: 1. Implement the interface; 2. Create the implementation of the interface classCases of object3Call a method through an object/ / the second step
Test02 test = new Test02();
/ / the third steptest.method(); }}/ / interface Test1
interface Test01{
public void method(a);
}
// Implement Test01
class Test02 implements Test01{

@Override
public void method(a) {
System.out.println("Methods that implement the Test interface"); }}Copy the code

[Using anonymous inner classes]

public class Test {
public static void main(String[] args) {
// If we need to use the method in the interface, we only need to take one step, using the anonymous inner class, and directly call itClass object is created.new Test1(){
public void method(a){
System.out.println("Methods that implement the Test interface"); } }.method(); }}interface Test1{
public void method(a);
}
Copy the code

New Test1(){code that implements methods in the interface}; Test1 () {… } is the role of the interface to implement, implement this interface here is just an anonymous class, the class don’t have a name that is to say, can only use this time, we know that this is a class, the new comes out, can get an implementation of a Test1 interface class instance of the object, through the instance objects, can call methods in the class, Because its anonymous class is implemented in a class, it is called an anonymous inner class. Don’t be puzzled why Test1(){… } is equivalent to the implementation of Test1 interface, the principle of which is powerful enough to learn, do not get to the point, here is just need to know what his role is, do something on the line.