Can you explain object orientation in a few sentences?

Can you explain object orientation in a few sentences?

1. process-oriented and object-oriented

1.1, process-oriented

The emphasis is on how I should do it . That is, the execution process of the function, that is, what to do first, and what to do later. In the process-oriented process, we will write a lot of functions, and each function is responsible for completing a certain function.

[Image upload failed...(image-777ba1-1625668972395)]

However, there are multiple small functions in a main function, which can be called sequentially when a certain function needs to be completed.

From this we found that the process-oriented design thought has the following shortcomings: poor system software adaptability, poor scalability, and low maintainability.

1.2, object-oriented

A new process-oriented programming idea. As the name suggests, the idea is to think about problems from the perspective of objects. We put multiple functions into different objects reasonably, emphasizing who should I do it.

The smallest object-oriented program unit is a class. The definition of the class must exist first, then the object, and the entity with a certain function is called an object

The difference between process-oriented and object-oriented is as follows:

Process-oriented and object-oriented have their own merits. Object-oriented is more in line with our conventional way of thinking . It has good stability, strong reusability, easy to develop large-scale software products, and good maintainability. It has three characteristics:

  1. Encapsulation
  2. inherit
  3. Polymorphism

2. variables

2.1. Classification of variables

According to the different locations of variable definitions, we can roughly divide variables into two categories:

  1. Member variable: directly defined in the class, outside the method, also called a field , not an attribute
  2. Local variables: Except for member variables, other variables are local variables, which only exist in methods, code blocks, and formal parameters of methods

2.2, the initial value of the variable

The initialization of variables means to open up a storage space in the memory for storage, which can only be used after initialization. Different variable types have different initial values

Member variables

There is an initial value by default, and different types of initial values are different

type of dataInitial default
byte, short, int, long0
float, double0.0
charA null character (space) "\u0000"
booleanfalse
Reference data typenull (means that no object is referenced

Local variable

Local variables have no initial value and must be manually initialized before they can be used

2.3, the scope of variables

Variables are defined in different positions, which also determine their respective scopes. The key is to look at the position of the curly braces where the variable is

Member variables

Are valid in the defined class

Local variable

It is valid from the position defined at the beginning to the curly braces, and invalid outside the curly braces

2.4, the life cycle of variables

The life cycle of a variable, in layman's terms, is how long the variable can live in memory

Member variables

Member variables belong to the object, the object is in the heap memory, so the member variables are also stored in the heap memory, and die with the demise of 1

Local variable

Local variables are stored in the stack memory and die with the end of the method call

Local variables are stored in the method. Each time the method is called, a memory space is opened up in the stack space. We become the stack frame. When the method 1 call ends, the stack frame is destroyed, and the variable data stored in the memory is also destroyed.

3. class

3.1, the definition of the class

A class is an abstraction of multiple objects with the same characteristics (state) and behavior (function)

  • Use member variables to represent state
  • Use member methods to express behavior

format

public class class name { //Can write 0 to N member variables Modifier data type variable name 1 ; Modifier data type variable name 2 ; //Can write 0 to N member methods Modifier return value type method name (parameter) { //Method body } } Copy code

note:

  1. Member methods and variables can not be modified with static , modifiers are not required
  2. In the class describing the object, there is no need to define the main method, the main method is written in a special test class, and the test class and the class describing the object are written separately

4. the object

4.1, the creation of the object

Class name object traversal name = new class name (); copy the code

If we print the object directly, it will print the hashCode value similar to the array address

4.2. Anonymous objects

After the object is created, it is not assigned to a certain traversal and can only be used once

new class name(); copy code

4.3, set data to the field

Object variable name. Field name = value; copy the code

4.4, get the data of the field

Data type variable = object variable. Field name; copy the code

4.5, object call method

Object variable name. Method (parameter); copy the code

4.6. Memory analysis of object instantiation

Simply analyze the Cat class below

public class Cat () { String name; int age; } Copy code

Create an object

Cat cat = new Cat(); Copy code

At this point, if you look at the name and age properties of the object, you can find that the initial values are null and 0, respectively.

Assign a value to the object

cat.name= "xiaolin" ; cat.age = 18 ; copy the code

Object call method

public class Cat () { String name; int age; public void say () { System.out.println( "Let s learn to meow together" ); } } Copy code

5. Constructor (construction method)

5.1, the definition of the constructor

Constructor, also known as Constructor, is used to create and initialize objects, and can only be used once when creating objects

The syntax of the constructor

public class name (parameter) { //method body } //Demonstration: public class Cat { public Cat () { } //Omit other codes } Copy code

Features of Constructor

  1. The constructor name is the same as the class name
  2. Cannot define return type
  3. The return statement cannot appear in the constructor

5.2, the default constructor

When we created the class, we did not manually write the constructor, and no error was reported. The reason is that if we are writing the object, if we do not write the constructor, the compiler will automatically create a default structure when compiling the source file. The characteristics of the default constructor: no parameters, no method body.

If the class uses public modification, then his default constructor will also use public modification, and vice versa

5.3. Use of Constructor

Before the constructor

Before, we first passed a default parameter constructor, first created an object and then initialized (set value for the field)

Cat cat = new Cat(); c.name = "xialin" ; c.age = 18;

public class Cat { String name; int age; public Cat(String name, int age) { this,name = name; this.age = age; } void say() { System.out.println(" " + name + ", " + age + " "); } }
Cat cat = new Cat("zs", 19); cat.say(); Cat cat = new Cat(); //

public class Cat { String name; int age; //No parameter constructor public Cat () { } //Constructor with parameters public Cat (String name, int age) { this ,name = name; this.age = age; } //Other code } Copy code

6. packaging

Encapsulation is one of the three characteristics of object-oriented, which has two meanings (to master the idea):

  • Store the fields and methods of the object in a separate module (class)

  • Information hiding, as far as possible to hide the implementation details of the object's data and functions

Benefits of encapsulation:

  • Ensure data security and prevent the caller freely modify data
  • Improve the reusability of components, put the common functions in a class, whoever needs the function, can directly call

The tool that restricts the field from being modified at will is the access modifier

6.1, access modifier

The access modifier determines whether there is permission to access a certain resource. The essence of encapsulation is to make some classes invisible to the fields and methods defined in other classes. Java provides different access permission modifiers to limit the members of the class who can access

ModifierInside the classSame packageSubclassAnywhere
private
no
protected
public
  • private: Indicates that the current class is private and can only be accessed in this class, and cannot be accessed directly after leaving this class
  • Don t write: it means that the current package is private, and the definition and call can only be in the same package for access
  • protected: Indicates the access rights of subclasses, the same package can be accessed, even if different packages have inheritance relationships, they can also be accessed
  • public: means public and can be accessed anywhere in the current project

Generally, private properties are provided in development and public access methods are exposed

6.2, JavaBean specification

JavaBean is a special class that meets certain conditions, but it must follow certain specifications:

  1. The class must be decorated with public
  2. It must be ensured that there is a public parameterless constructor, even if a parameterized constructor is provided manually, a parameterless constructor must
  3. The segment is decorated with private, and each field provides a pair of getter and setter methods
public String getName () { return name; //Returns the value stored in the name field } public void setName (String n) { name = n; //Store the value of the passed parameter n in the name field } Copy code

6.3. Constructor and setter methods

Both the constructor and the setter method can set data for the object:

  • The constructor, which sets the initial data when creating the object, can only be initialized once.

  • The setter method, set the initial data after the object is created, can be set multiple times.

7. inheritance

Object-oriented inheritance ideas can solve the problem of common code in multiple classes

  • The inherited class is called the parent class and base class

  • The class that inherits the parent class is called the subclass, and the extended class

  • Parent class: store the fields and methods common to multiple subclasses

  • Subclass: store your own unique fields and methods

7.1, the syntax of inheritance

In the program, if a class needs to inherit another class, use the extends keyword at this time

public class subclass name extends parent class name { } Copy code

Note: Classes in Java only support single inheritance, not multiple inheritance, but support multiple inheritance. That is to say, a subclass can only have one direct parent, and the parent can also have a parent. A parent class can also have multiple subclasses

class student1 () ; class STUDENT2 () ; class Student Extend student1 , STUDENT2 () {}//Error copy the code

The Object class is the root class of the Java language. Any class is a subclass of Object, either a direct subclass or an indirect subclass

7.2. Which members of the parent class can be inherited by the subclass

After the subclass inherits the parent class, it can have certain members (fields and methods) of the parent class, which can be judged according to the access modifier :

  1. Members of the parent class modified with public and protected can be inherited by subclasses
  2. If the parent class and the subclass are in the same package, the default access modifier is used, and the subclass can inherit
  3. If the members of the parent class are decorated with private , the subclass can not inherit it, because private can only be accessed in the Benben class
  4. The constructor of the parent class cannot be inherited by subclasses, because the constructor must be the same as the class name

7.3. Method rewriting

When a subclass has a method exactly the same as the parent class, we call it the subclass covering the superclass's method, which is also called rewriting . Then we can rewrite the logic code in the subclass method body

The order of method calling is: when calling a method through an object, first find out if there is a corresponding method in the subclass, if it exists, execute the subclass, if the subclass does not exist, execute the parent class, if the parent class does not exist, report an error .

Points to note for method rewriting:

  1. Private modified methods cannot be inherited by subclasses, so there is no concept of overriding
  2. Instance method signatures must be the same (method signature=method name+method parameter list)
  3. The return value type of the subclass method is the same as the return value type of the parent class or its subclass
  4. The exception thrown by the subclass method declaration is less than or equal to the exception type thrown by the parent class method declaration
  5. The access rights of the subclass methods are greater or equal than the access rights of the parent class
  6. General development is to directly copy the method definition of the parent class and paste it into the subclass, and rewrite the method body of the subclass

7.4, super keyword

In a certain method in the subclass, you need to call the overridden method in the parent class. In this case, you must use the super keyword.

If the super keyword is not used to call the overridden method, the method in this class is called at this time. The super keyword represents the meaning of the parent object

7.5, abstract

Abstract methods use abstract to modify methods, and the methods modified by abstract have two characteristics:

  1. This method has no method body
  2. Requires that subclasses must override this method

7.5.1, abstract method

The method of using abstract modification is called abstract method

public abstract return type method name (parameter); copy code

The characteristics of abstract methods:

  1. Use abstract modification, no method body, leave it to subclasses to cover
  2. Abstract methods must be defined in abstract classes or interfaces

7.5.2, abstract class

Classes decorated with abstract are called abstract classes

public abstract class class name { } Copy code

The characteristics of abstract classes:

  1. An abstract class cannot create an object, and calling an abstract method without a method body has no meaning
  2. Abstract classes can have abstract methods and ordinary methods at the same time
  3. An abstract class must have a subclass to make sense, and the subclass must override the abstract method of the parent class, otherwise the subclass must also be used as an abstract class

7.6, Object class and common methods

Object itself means the object, it is the root class in Java, either the direct parent of a class or the indirect parent of a class. Any class directly (indirectly) inherits the Object class

class A {} //equivalent to the class A the extends Object {} copy the code

Because all classes are subclasses of the Object class, all objects of the class can call methods in the Object class, and the frequently used methods are

7.6.1, boolean equals(Object obj)

boolean equals(Object obj): compare the object currently calling the method with the parameter obj

The equals method in the Object class is the same as the "==" symbol, which compares whether the object is the same storage address.

public class ObjectDemo { public static void main (String[] args) { //Create Person object p1 Person p1 = new Person(); //Create Person object p2 Person p2 = new Person(); //Compare whether the memory addresses of p1 and p2 are the same boolean ret1 = p1 == p2; boolean ret2 = p1.equals(p2); System.out.println(ret1); //false System.out.println(ret2); //false } } Copy code

7.6.2, toString method

toString means to convert the field information in the object into a string format

The printing object is actually the toString() method of the printing object, but the toString() method prints the value of the hashCode of the object by default

com._04_object.Person@15db9742Copy code

So generally we will rewrite the toString() method

public String toString () { return "Person [name=" + name + ", age=" + age + "]" ; } Copy code

7.7 Detailed explanation of the == symbol

Every time you use the new keyword, it means to create a new memory space in the heap memory

  • If it is a basic data type: the comparison is whether two values are equal
  • If it is the object data type: compare whether it is the same memory address

8. Polymorphism

8.1. Interface

Interface is a convention specification, ** is a collection of multiple abstract methods**. It only defines what functions should be provided, and does not implement the functions itself. As for how to implement each function, it is left to the implementation class to complete. The methods in the interface are abstract methods and do not provide functional implementation. ** It reflects the idea of separation of specification and implementation, and also reflects the idea of low coupling between components**. The interface only provides the definition of the method, but does not provide the code implementation of the method The so-called coupling degree indicates the dependency between components. The more dependencies, the stronger the coupling, and the poorer the independence of the component. In development, it is often advocated to reduce the coupling, which can improve the independence of its components. Give a very simple example: Copy code
  • Integrated graphics card: the graphics card and the motherboard are welded together, the graphics card is broken, and the motherboard can only be replaced
  • Independent graphics card: The graphics card and the motherboard are separated, and the graphics card can be plugged into the motherboard.

8.1.1, the definition of the interface

Interface can be considered as a special class, but the class keyword is used when defining the class, and the interface keyword is used to define the interface. The methods in the interface are all public abstract methods

public interface interface name { //abstract method 1(); //abstract method 2(); //abstract method 2(); } Copy code

Note: Starting from Java 8, Java supports the definition of implemented methods in the interface

public interface IMan { public abstract void walk () ; //Abstract method default void defaultMethod () { System.out.println( "There are methods implemented by default, belonging to objects" ); } static void defaultMethod () { System.out.println( "There are methods implemented by default, belonging to the class" ); } } Copy code

Classes can inherit classes, but only single inheritance, interfaces can also inherit interfaces, but they can inherit multiple interfaces , which means that an interface can inherit multiple interfaces at the same time

8.1.2, interface implementation class

Like abstract classes, interfaces cannot create objects. If you want to implement the functions of the interface, you must define a class to implement the interface and cover all the methods in the interface. This class is called the implementation class. The relationship between this class and the interface Realization relationship

public class class name implements interface name { //override abstract methods in the interface } Copy code
  • Interface: Define multiple abstract methods, only define what functions are there, without any implementation

  • Implementation class: implement the interface, rewrite the abstract methods in the interface, and complete the realization of specific functions

8.2, polymorphism

In the inheritance relationship, it is a kind of "is A" relationship, which means that the subclass is a special case of the parent class

public class Animal {} public class Dog the extends Animal {} public class Cat the extends Animal {} copy the code

At this point, we can think that cats and dogs are both special animals, so we can use animal types to represent cats or dogs

= Dog Dog new new Dog (); //create a dog object type variable is assigned to the subclass Animal Animal = new new Cat (); //create a cat object is assigned to the parent class type variable copy the code

At this time, the animal object has two types:

  1. Compilation type: the type when the object is declared (Animal)
  2. Operation type: the real type of the object (Cat)

When the compilation type and the running type are inconsistent, polymorphism occurs

The so-called polymorphism means that an object has multiple forms, in simple terms it is the same reference type, because the referenced instance is different, the result of the same method is also different

Person person = null ; = Person new new Man (); //this case represents Man Type Person Person = new new Woman (); //this case represents Woman Person Type duplicated code

Polymorphism must be based on method rewriting or implementation. It can be an inheritance relationship (class and class) or an implementation relationship (interface and implementation class). In development, it generally refers to the relationship between interface and implementation class , Polymorphism has two definition formats in development

8.2.1. Operational inheritance relationship (not many in development)

The parent class reference variable points to the subclass object, and the method of the subclass is actually called when the method is called

Parent class variable name = new subclass(); Variable name.method(); Copy code

Animal class:

public class Animal { public void shout () { System.out.println( "animal... called..." ); } } Copy code

Cat category:

public class Cat extends Animal { public void shout () { System.out.println( "Meow..." ); } } Copy code

Test class:

public class AnimalDemo { public static void main (String[] args) { Animal animal = new Cat(); animal.shout(); } } Copy code

operation result:

Meow copy the code

8.2.2, operation realization relationship

Interface variable name = new implementation class(); Variable name.method(); Copy code

ISwimable interface:

public interface ISwimable { void swim () ; } Copy code

Fish category:

public class Fish implements ISwimable {} public void swim () { Sysout.out.println( "Fish is swimming" ) } } Copy code

Test class:

public class Fish implements { public static void main (String[] args) { ISwimable fish = new Fish(); fish.swim(); } } Copy code

result:

Fish swim copy the code

8.2.3, method call problem in polymorphism

If we assign the subclass object to the parent class object

Animal animal = new Cat(); animal.shout(); Copy code

So when the animal object calls the shout method, does it call the method of the subclass or the method of the parent class?

We can see that at compile time, the JVM will first look for the method of the parent class, and if it finds the method of the subclass with the same name, if the subclass also has the method of the subclass, run the method of the subclass, otherwise it will run the method of the parent class. , If the method of the parent class is not found, the compilation fails directly

8.2.4, type conversion and instanceof operator

8.2.4.1, automatic type conversion

Automatic type conversion: assign subclass objects to parent variables (polymorphism)

Animal a = new Dog(); Obj = Object new new Dog (); //Object class is the root class of all duplicated code

8.2.4.2, forced type conversion

Assign the parent type object to the child type variable (premise: the real type of the object should be the child type)

When you need to call a method specific to a subclass, you must go through a forced type conversion, but there is a requirement: the parent class must be a real subclass type before it can be converted

Animal a = new Dog(); D = Dog (Dog) A; //correct Cat C = (Cat) A; //error type is real Dog duplicated code

8.2.4.3, instanceof operator

Determine whether the object is an instance of a certain class

Grammatical format

boolean b = object A instanceof class B;//Judging whether object A is an instance of class B? If so, it returns true copy the code

8.2.4.4, polymorphism summary

Interface-oriented programming embodies polymorphism, and its benefits: assign implementation class objects to interface type variables, shielding the implementation differences between different implementation classes, so that universal programming can be achieved

8.3 Interview questions

The difference between interface and abstract class

  1. All the methods in the interface are implicitly abstract, but the abstract class can contain both abstract methods and ordinary methods as well as static constants
  2. Class can implement many interfaces, but can only inherit one abstract class
  3. If a class wants to implement an interface, then it must implement all the methods declared by the interface, but the class does not need to implement all the methods in the abstract class, but the class must be an abstract class
  4. There is no construction method in the interface, because the member variables of the interface are static final variables, the initialization operation is completed at the time of compilation, there is no need to initialize the operation through the construction method, and the abstract class must have a construction method
  5. The difference between the concepts of abstract classes and interfaces:
    • Abstract classes extract their common attributes from some classes. The modifiers of methods can be public or protected and default. Abstract classes focus on the abstraction of the class itself. Abstract methods have no method body, but only declare the method. Let inherited his subclass to achieve
    • The interface is mainly to abstract the behavior of the class, and the interface can also have variables and methods, but the modifiers of the variables and methods must be public static final (it will be added by default) and public abstract (this is also the default by default)

9. keywords (this, super)

9.1, this keyword

this
The keyword indicates that the current object (who calls the method where this is, this is the main object) exists in two places:

  1. In the constructor: represents the currently created object
  2. In the method: which object calls the method where this is, at this time this represents which object

When do you need to use this keyword

  1. In order to resolve the ambiguity between local variables and member variables, you must use
  2. The mutual call between non-static methods in the same class can be omitted at this time, but basically will not be omitted
  3. Call other construction methods of this class
public class Dog { private String name; private int age; public Dog () { } public Dog (String name) { this (name, 0 );//call the constructor with two parameters (overload between constructors), must be placed in the first line of the constructor } public Dog (String name, int age) { this .name = name; this .age = age; } public void say () { String name = "Local Variable" ; System.out.println(name); //access local variables System.out.println( this .name); //access member variables this .other(); //call non-static methods in the current class } public void other () { System.out.println( this .age); //Who is this at this time } } Copy code

this memory graph

The this keyword represents the current object itself, which is generally used inside the class, and there is an address inside it that points to the current initialization object itself

When an object is new, two references are actually generated. One is the this keyword for calling other member variables or member methods inside Dog, and the other is the dog holding class information for external programs to call instance members.

9.2, super keyword

super represents the parent class object of the current object. When creating a subclass object, the superclass constructor will be called first in the first line of the subclass constructor

Although super represents the parent object, it is only a keyword, and there is no address inside, so it cannot be referenced

When to use super

  1. To access non-private instance methods in the parent class, you must use super at this time
  2. In the constructor of the subclass, call the constructor of the parent class, you must use super at this time
  3. If you want to access the non-private member variables of the parent class, you must use super at this time

father:

public class Person { private String name; private int age; public Person () { } public Person (String name, int age) { this .name = name; this .age = age; } public void doWork () { System.out.println( "Person...doWork..." ); } } Copy code

Subclass:

public class Student extends Person { private String sn; public Student (String sn) { super ();//implicitly call the parent class no-parameter constructor, which must be the first line of the construction this .sn = sn; } public Student (String name, int age, String sn) { super (name, age);//Show that there is a parameter constructor to call the parent class, which must be the first line of the construction this .sn = sn; } public void doWork () { super .doWork(); //call the doWork() method of the parent class at this time this .doWork(); //call your own doWork() method System.out.println( "Student. ..doWork..." ); } } Copy code

summary

  1. The super call constructor must be written in the first line of the subclass constructor
  2. If the subclass construction method does not show that the parent class construction method is called, then the JVM will call the parent class's no-argument constructor by default

10. Modifiers (static, final)

10.1 static modifier

The fields and methods modified by static belong directly to the class, and not to the objects of the class (the field and method belong to whoever calls it)

  • Variables and methods modified with static: belong to the class, and can be called directly by the class name. In the same class, the class name can be omitted and the class name can be omitted.
  • Variables and methods without static modification: belonging to an object, the object must be created first, and then called with the object

Note: static method cannot use super and this keywords

Because static is at the class level, super and this are at the object level. When a class exists, an object may not exist. In other words, when a static method is called with a class name, there may be no object at this time. Copy code

10.1.1, static method

Static modified methods are called static methods, classified as all, also known as class methods

Modifier static return value type method name (parameter list) { } Copy code

There are two ways to access static methods:

  1. Class name. Static method name ()
  2. Object. Static method name () Java does not recommend this access mechanism

Characteristics of static methods

  1. Static variables and other static methods can be accessed in static methods
  2. Static member variables and static member methods can be accessed in instance methods

10.1.2, static variables

In the class, member variables modified with the static keyword called a static variable, which is classified as a class variable, and is also called a class variable. All instance objects of the class can be accessed and shared by all instances or objects of the class.

static data member variable type copy the code

Static variable access

  1. Class name. Static variable

  2. Object of the class. Static variable ( Java not recommended )

10.2 final modifier

The meaning of final is final and unchangeable. It can modify classes, methods, and variables. It is to restrict a certain class from having subclasses or overriding methods.

final modified class

Represents the final class, which can no longer have subclasses

final public class Super { } public class Sub extends Super { //Syntax error on this line } Copy code

final modified method

The final method, this method cannot be overridden by subclasses

public class Super { final public void doWork () { } } public class Sub extends Super { public void doWork () { //This line of syntax error } } Copy code

final modified variable

Represents a constant, the variable can only be assigned once, and cannot be re-assigned

  • Basic data type: the value represented can no longer be changed
  • Reference data type: the referenced address can no longer be changed
final int age = 17 ; age = 100 ; //Syntax error on this line final Dog d = new Dog(); d.setAge ( . 5 ); field value//d can be changed to D = new new Dog (); //This line syntax error duplicated code

Eleven, code block

Directly use a section of code area enclosed in {}, the variables in the code block are local variables and are only valid in {}

It has three forms of existence: ordinary code block, structured code block, static code block

11.1 Ordinary code block

The code block directly defined inside the method, generally, will not directly use the local code block, combined with keywords such as if, while, for, and so on, represents a code area, the scope can be nested

public class CodeBlockDemo { public static void main(String[] args) { System.out.println("begin..."); { //Use the code block directly, generally do not use int age = 17; } System.out.println(age); //This line reports an error, beyond the scope of age, you cannot access if ( 100 >5) { System.out.println( "100> 5"); } System.out.println( "end..."); } } Copy code

11.2, constructing code blocks

The construction code block is inside the class and outside the method. It is executed once with the creation of an object, and executed before the method is constructed.

package day09_ObjectAdvanced.Classing.StaticBlock; /** * @author Xiao_Lin * @version 1.0 * @date 2020/12/9 16:29 */ public class Dog { private String name; static String age = "111" ; { System.out.println("I am a construction code block" ); } public Dog () { System.out.println( "I am a parameterless construction method" ); } public Dog (String name) { System.out.println( "I am a parameter construction method" ); } public void shut () { System.out.println( "I am calling method" ); } } Copy code

[Image upload failed...(image-1f329c-1625668972395)]

If you need to load some resources (such as reading configuration files, XML files, etc.) before the execution of the construction method, we can put all operations before constructing the object in the construction code block for execution

11.3, static code block

The code block modified with the static keyword is called a static code block, which is located inside the class and outside the method, and is executed only once, before the construction code block and the construction method

package day09_ObjectAdvanced.Classing.StaticBlock; /** * @author Xiao_Lin * @version 1.0 * @date 2020/12/9 16:29 */ public class Dog { private String name; static String age = "111" ; static { System.out.println( "I am a static code block" ); } { System.out.println( "I am a construction code block" ); } public Dog () { System.out.println( "I am a parameterless construction method" ); } public Dog (String name) { System.out.println( "I am a parameter construction method" ); } public void shut () { System.out.println( "I am calling method" ); } } Copy code

[Image upload failed...(image-84d6a2-1625668972395)]

12. Internal category

12.1 The organization of classes

12.1.1, the parallel relationship between classes and classes

A file can define multiple classes, but only one public class can exist, and the name of the file must be consistent with the name of the public class

public class Dog { } class Cat { } Copy code

[Image upload failed...(image-7d962f-1625668972395)] Dog and Cat have the same status, which is exactly the same as defining two files separately

12.1.2, the relationship between classes and classes

public class Outer { public class Inner { } } Copy code

Outer and Inner are contained relationships. Outer is called an external class, and Inner is called an inner class. The inner class Inner exists as a member of Outer [Image upload failed...(image-a63ec6-1625668972395)]

12.2 Overview of internal classes

What is an inner class? Define a class inside another class, call the inner class an inner class, and call the outer class an outer class. The classifications of inner classes are:

  1. Member inner class
  2. Static inner class
  3. Method inner class
  4. Anonymous inner class

12.3, anonymous inner class

When a class is used only once, it can be declared as an anonymous inner class

Anonymous inner classes must have implementations, and most of them implement interfaces

public class Outer { public void print () { /* class Inner implements AInterface{ @Override public void showInfo() { System.out.println("inner.showInfo"); } } new Inner().showInfo(); */ /* AInterface aInterface = new AInterface(){ @Override public void showInfo() { System.out.println("inner.showInfo"); } }; aInterface.showInfo(); */ //Create anonymous objects through anonymous classes new AInterface(){ @Override public void showInfo () { System.out.println( "inner.showInfo" ); } }.showInfo(); } } Copy code

Thirteen, enumeration class

Enumeration is a special class, which fixes which objects a class can only have

13.1 Definition of enumeration class

public enum enumeration type { constant object A, constant object B, constant object C } Copy code
publicc enum Story { HISTORY, ENGLISH, MATH } Copy code

Our custom enumeration classes are directly inherited at the bottom

java.lang.Enum
Classes, enumerations are all global public static constants, which can be called directly with the enumeration class name

Stroy story = Story.ENGLISH; copy the code

Because the java.lang.Enum class is the parent class of all enumeration classes, all enumeration objects can call the methods in the Enum class

String name = enumeration object.name(); //return the constant name of the enumeration object int ordinal = enumeration object.ordinal(); //return the serial number of the enumeration object, copy the code from 0

Note: Enumeration classes cannot be used to create objects