I hear you don't know object-oriented yet?-- Hardest core ever, object-oriented from entry to proficiency

๐Ÿ“œ Personal profile

โญ Personal Home Page: Touch Fish and Sauce Blog Home Page๐Ÿ™‹โ€โ™‚๏ธ
๐Ÿ‘ Blogging: java programming basics, mysql
๐Ÿ… Writing style: dry, dry, or tmd dry
๐ŸŒธ Selected Columns: [Java][mysql] [algorithmic brush notes]
๐ŸŽฏBlogger's code cloud gitee, bloggers usually write program code inside.
๐Ÿš€ Support blogger: compliment ๐Ÿ‘, Collection โญ, Leaving a message. ๐Ÿ’ฌ
๐Ÿญ Author's level is limited. If you find any errors, you must inform the author in time. Thank you!

๐Ÿ’› Preface:

_Believe that you will always hear about Java when you come into contact with it: Java is an object-oriented programming language, and the c language we learned before is a process-oriented programming language. So many children's shoes don't know what this object-oriented means or where it is reflected in the process of learning java, even after they have finished.
However, to learn the language well, it is necessary to master object-oriented, especially when we face a large project, hundreds of thousands of lines of code, object-oriented will let you know its magic.
_Then let me take you to dig into object-oriented details today. I believe that after reading this article, you will have a clear and thorough understanding of object-oriented.

(Article Catalog Strip โญ _For the key points to master)

Are you ready? We're getting started!


)

๐Ÿ‘“ Understanding Object Oriented

First, serve the main course ๐Ÿ” Let's order an appetizer first ๐ŸŸ: Let's get to know what object-oriented is

_ ๐Ÿšฉ When it comes to object-oriented (OOP), there is no need to mention process-oriented (POP).

_ โ“ So, what is the difference between the two brothers?
_1 ๏ธโƒฃ Both are ideas: object-oriented is relative to process-oriented.
Process-oriented, which emphasizes the functional behavior, takes the function as the smallest unit, and considers how to do it.
_Object-oriented, encapsulates functions into objects, emphasizes objects with functions, takes class/object as the smallest unit, and considers who to do it.
_2 ๏ธโƒฃ Object-oriented emphasizes more on the use of human thinking methods and principles in daily thinking logic, such as abstraction, classification, inheritance, aggregation, polymorphism, and so on.
_3 ๏ธโƒฃ. Object-oriented Thinking Transforms programmers from process-oriented executors to object-oriented commanders.

The above is a more official explanation of the difference between the two, but I believe you now have a feeling of "listening to the voice of the emperor, such as listening to a voice".
Still not understood. No problem. Let me give you a practical example to help you understand the above:
A classic example: putting an elephant in the refrigerator

_If we do this with a process-oriented mind, all we need to do is open the door of the refrigerator first --> tuck the elephant in --> close the door of the refrigerator... This is done in a series of actions.
_What if it was done as object-oriented?
_As mentioned earlier, the object-oriented question is who does it. Let's see that this operation involves several objects - people, refrigerator, elephants, three objects altogether. For people: to open (close) the door of the refrigerator, and to complete the operation of loading the elephant into the refrigerator. For the refrigerator: complete the opening and closing of the door. Finally for elephants: to enter the refrigerator


OK, after looking at the above examples, I believe that your smart buddies have a preliminary understanding of what is object-oriented. ๐Ÿ˜Ž

We also want to understand two object-oriented elements: classes and objects
Many small partners do not have a good understanding of classes and objects during java learning, which can affect later learning. So first we need to look at classes and objects:

๐Ÿ‘“ Understanding Classes and Objects

Class and Object are core object-oriented concepts.
1 ๏ธโƒฃ Classes are descriptions of similar things, abstract and conceptual definitions
2 ๏ธโƒฃ An object is each individual of this kind of thing that actually exists, hence also known as an instance, and it is a specific individual.

โ“ So how do you really understand these two concepts?

_ ๐Ÿ”Ž Classes are descriptions of individuals who share common characteristics and behave similarly.
For example, Xiao Ming and Xiao Hong have some attributes such as name, age and gender, and they can learn, communicate with others, and other similar behaviors. Because these two people share these similarities, we abstract them and define them as a class, human.
_but the object is really concrete.
For example, Xiao Ming and Xiao Hong are the individuals (objects) in the human class.

Class Instantiation

๐Ÿšฉ The process of creating an object with a class type, called instantiation of a class

Grammar Format

// Create Class
class <class_name>{
	field;//Member Properties
	method;//Member Method
}
// Instantiate Object
<class_name> <Object Name> = new <class_name>();
  1. A class is simply a model-like thing that defines what members it has.
  2. A class can instantiate multiple objects, which take up the actual physical space and store class member variables

Example:

class Person {
    public int age;//attribute
    public String name;
    public String sex;
    public void eat() {//Method
        System.out.println("Having dinner!");
    }
    public void sleep() {
        System.out.println("Sleep!");
    }
}
public class Classes and Objects {
    public static void main(String[] args) {
        Person person = new Person();//Instantiate objects through new
        //Generate multiple objects
        Person person2 = new Person();
        Person person3 = new Person();
    }
}

Summary
1.The new keyword is used to create an instance of an object.
2.Use. To access the properties and methods in the object.
3. The same class can create pairs of instances.

Next, I'll start from 1 ๏ธโƒฃ: Classes and class members, 2 ๏ธโƒฃ : Three Object Oriented Features, 3 ๏ธโƒฃ : The other three keywords describe the object-oriented features. This article is about classes and members of classes

๐Ÿšฉ The focus of object-oriented programming is the design of classes

class Person{}  

Like this, it's already a person class. But there's nothing inside this kind of thing, just an empty shell, no soul
We'll design him to make it work.

๐Ÿšฉ The essence of a design class is that it is a member of a design class
_where the members of a class are: attributes, methods, constructors, code blocks, internal classes

Among these five categories, the most basic and important are: attributes (Field s are also called variables, but also fields or domains), (members) methods.

๐ŸŒŸ 1. Attributes (variables)

๐Ÿ’™ Variable classification:

๐Ÿšฉ Variables can be divided into member variables and local variables depending on where they are declared

๐ŸŒ€ local variable

๐Ÿ’Ž Within a method (method parameters, internal classes, code blocks, constructors (constructor parameters)) are declared local variables

โ„๏ธ Declaration Format

Variable type variable name = variable value;

โ„๏ธ Characteristic

1 ๏ธโƒฃ. Access qualifier modifier cannot be used when declaring, its permissions follow the permissions of the method (or constructor).

2 ๏ธโƒฃ. Following the principle of assignment followed by use, uninitialized local variables cannot be used directly (Note: Method parameters are special, and its initialization is the value passed in when the method is called;)

That means we have to explicitly assign a value before we call a local variable
3 ๏ธโƒฃ. Local variables are stored in stack space

Example:

class Person {
    public String name;
     public void eat() {//Method
     	int a = 10;
     	int b;
        System.out.println("Having dinner!");
    }
}

โ„๏ธ Summary

๐ŸŒ€ Member variables

๐Ÿ’Ž Declare inside class, outside method is member variable

Declaration Format:

Permission modifier (static) variable type variable name = variable value;

Depending on whether or not the declaration has a "static" modification, it can also be divided into: normal member variables (without static modification) and static member variables.

Next, the similarities and differences between common member variables (also called instance variables) and static member variables (also called class variables) are discussed.

โ–ถ๏ธ Same point

1 ๏ธโƒฃ. Both need to be declared before being used, either by default (0/null) or by initializing other values
_Initialization value for default initialization:
_Integer variables: byte, short, int, long ----> 0
_Floating-point type: float, double ----> 0.0
Boolean ---->false
Character type: char ---->0 or'u0000'
Reference type: interface, array, class-->null
2 ๏ธโƒฃ. Permission modifiers can be declared; Modifiers are public, default, protected, private;
3 ๏ธโƒฃ. Instance variables all have a scope {} in which they are located and are valid only in the scope they are defined.

Example:

class Person {
    private static String name;//Static member variable
    public  int age;//Common member variable
}
class Animal{
    public String a_name;
}
public class Classes and Objects {
    public static void main(String[] args) {
        Animal animal = new Animal();
        animal.age   //age is defined in the Person class and can only be called by objects in the Person class
    }
}

โ–ถ๏ธ Difference

1 ๏ธโƒฃ. Declare differently

๐Ÿ”บ Instance variables do not require static modification
๐Ÿ”ป Class variables require static modification

2 ๏ธโƒฃ. Called differently

๐Ÿ”บ Instance variables cannot be called without instantiation. By object. Property modifies this instance variable;
๐Ÿ”ป Class variables can be called not only through objects, but also by class names. Method calls to class variables;

class Person {
    public static int age;//Static member variable
    public String name;//Common member variable   
}
public class Classes and Objects {
    public static void main(String[] args) {
        Person person = new Person();//Instantiate objects through new
        System.out.println(person.sex);//Object. Instance variable
        System.out.println(person.age);//Object. Class variable
        System.out.println(Person.age);//Class. Class variable
        System.out.println(Person.name);//Cannot directly classes. Instance variable
    }
}

3 ๏ธโƒฃ. Different life cycles

๐Ÿ”บ Instance variables are created as objects are created and released as objects are recycled.
๐Ÿ”ป Class variables occur as classes are loaded and disappear as classes disappear

4 ๏ธโƒฃ. Unlike object relationships

๐Ÿ”บ Instance variables Each object has a unique instance variable and does not interfere with each other, so it is also called the object's unique data.
๐Ÿ”ป Class variables are shared by all objects of the class. Once changed, subsequent calls are changed values, so they are also called shared data of objects.

Example:

class Person {
    public static String name;//Static member variable
    public  int age;//Common member variable
    public String sex;
}
public class Classes and Objects {
    public static void main(String[] args) {
        Person person1 = new Person();//Instantiate objects through new
        person1.name = "Zhang San";
        person1.age=10;
        System.out.println(person1.name);
        System.out.println(person1.age);
        System.out.println("=========================================");
        Person person2 = new Person();
        System.out.println(person2.name);
        System.out.println(person2.age);

    }
}

5 ๏ธโƒฃ. Storage space is different

๐Ÿ”บ Instance variables are stored in objects in heap memory
๐Ÿ”ป Class variables are assigned in the static zone of the method area, which precedes method creation and object existence.

Memory parsing diagram

๐Ÿ’™ Anonymous object

Instead of defining a handle to an object, we can call its method directly. Such objects are called anonymous objects.
E.g. new Person().shout();
๐Ÿ“• Usage
_1. Anonymous objects can be used if there is only one method call to an object.
_2. We often pass anonymous objects as arguments to a method call.

๐Ÿ’™ About object arrays

What is an object array?
_We can learn about it by analogizing structured arrays in c.
_The so-called object array refers to the inclusion of a set of related objects, but it must be clear in the use of the object array: the array must first open up space, but because it is a reference data type, each object in the array initialization is a null value, then each object in the array must be instantiated separately when used.

class Student{
	int number;//School Number
	int state = 1;//grade
	int score;//achievement
}
public class object array {
    public static void main(String[] args) {
        Student[] stus = new Student[5];
		stus[0] = new Student();
        System.out.println(stus[0].state);//1
        System.out.println(stus[1]);//null
        System.out.println(stus[1].number);//Error, stus[1] has not instantiated object at this time, it is null
        stus[1] = new Student();
		System.out.println(stus[1].number);//0
    }
}

Memory parsing diagram:

โญ Differences between member variables and local variables

๐Ÿ’™ Summary

๐ŸŒŸ 2. Method

๐Ÿ’™ What is the method

_1 ๏ธโƒฃ. A method is an abstraction of the behavior characteristics of a class or object used to perform a functional operation. In some languages
Also known as a function or procedure.
_2 ๏ธโƒฃ. The purpose of encapsulating functionality as a method is to achieve code reuse and simplify code
_3 ๏ธโƒฃ Methods in Java cannot exist independently; all methods must be defined in classes.
_4 ๏ธโƒฃ. Let's see if a class is powerful, mainly because of the richness of its internal methods.

๐Ÿ’™ Method declaration format

Modifier Return Value Type Method Name (Parameter Type Parameter 1, Parameter Type Parameter 2,....))
_Method Body Program Code
_return return return value;
๏ฝ

among
1 ๏ธโƒฃ. Permission modifier: public protected default private;
2 ๏ธโƒฃ. Return value type:
There is no return v a lue: void
There is a return value, declaring the type of return value. Use with "return return return value" in method b ody
3 ๏ธโƒฃ. Method name: belongs to the identifier, which follows the rules and specifications of identifier naming, and can be viewed concretely. Variable Naming Rules
4 ๏ธโƒฃ. Parameter list: can contain zero, one or more parameters. Separate multiple parameters with "," in the middle
5 ๏ธโƒฃ. Return value: The data returned by the method to the program calling it after execution.

๐Ÿ“ƒ Reflection
How do you understand when the method return value type is void?

Depending on whether or not the declaration has a "static" modifier, methods can be divided into normal member methods (without static modifiers) and static member methods

๐Ÿ’™ Classification of methods

No return valueHas Return Value
Invisible parametervoid method name (){}Type method name () {} of return value
Tangible parametersvoid method name (parameter list)Type method name (parameter list) {} of return value

๐Ÿ’™ Call to method

๐Ÿ’Ž The method is called by the method name and will only execute if called.

Process analysis of method calls

Be careful:
1 ๏ธโƒฃ Method is called once and executed once
2 ๏ธโƒฃ In the absence of a specific return value, the return value type is represented by the keyword void, so the return statement may not be necessary in the body of the method. If used, use only to end the method.
3 ๏ธโƒฃ When defining a method, the result of the method should be returned to the caller and handled by the caller.
4 ๏ธโƒฃ Methods can only call methods or properties, not define methods within methods.

โญ Overload of method

๐ŸŒ€ The concept of overloading

Java allows multiple methods with the same name to be defined in the same class as long as their parameter lists are different. If the same class contains two or more methods with the same method name but different parameter lists, this is called method overload.

๐ŸŒ€ Characteristics of overload

๐Ÿ’Ž Method overload requires two identical things: the same method name and different parameter lists in the same class. Other parts of the method, such as method return value types, modifiers, and so on, have nothing to do with method overloading.

Example:

public class OverLoading {
    public void max(int a, int b) {
        // Method with two parameters of type int
        System.out.println(a > b ? a : b);
    }

    public void max(double a, double b) {
        // Method with two double type parameters
        System.out.println(a > b ? a : b);
    }

    public void max(double a, double b, int c) {
        // Method with two double type parameters and one int type parameter
        double max = (double) (a > b ? a : b);
        System.out.println(c > max ? c : max);
    }

    public static void main(String[] args) {
        OverLoading ol = new OverLoading();
        System.out.println("1 Compared with 5, the larger ones are:");
        ol.max(1, 5);
        System.out.println("5.205 And 5.8 By comparison, the larger ones are:");
        ol.max(5.205, 5.8);
        System.out.println("2.15,0.05,58 Medium, larger:");
        ol.max(2.15, 0.05, 58);
    }
}

๐Ÿ‘‰ Overloaded methods can be used for programming convenience, in fact, to avoid a large number of method names. Some methods have similar functions. If you re-establish a method and re-choose a method name, the readability of the program will be reduced.

โ“ Seeing this, you must be asking: Why can't different types of return values be used as overloaded conditions?
_For both methods of int f() {} and void() {}, if int result = f() is called in this way; The system can identify a method that calls a return value of type int
_However, when Java calls a method, the method return value can be ignored if f() is called in the following way; Can you tell which method to call?
_If you don't know yet, the Java system will be confused. One of the important rules in programming is not to let the system get confused. If the system gets confused, you must be wrong. Therefore, method return value types cannot be used as a basis for distinguishing method overloads in Java โ— .

๐Ÿ’™ Methods for Variable Parameters

_JavaSE 5.0 provides a Varargs(variable number of arguments) mechanism that allows direct definition of parameters that can match multiple arguments. This allows you to pass in a simpler way a variable number of arguments

//Prior to JDK 5.0: Array parameters were used to define methods that passed in multiple variables of the same type
public static void test(int a ,String[] books);
//JDK5.0: Variable number of parameters to define the method, passing in multiple variables of the same type
public static void test(int a ,String...books);

๐Ÿ’ก Explain:
1 ๏ธโƒฃ. Declare format: Method name (type name of parameter... parameter name)
2 ๏ธโƒฃ . Variable parameters: The number of parameters of the type specified in the method parameter section can be variable: 0, 1, or more
3 ๏ธโƒฃ . Methods with variable number of parameters form overloads with methods with the same name
4 ๏ธโƒฃ. The use of variable parameter methods is consistent with the use of arrays in the method parameter section and cannot constitute an overload.
5 ๏ธโƒฃ. The parameter part of the method has a variable parameter and needs to be placed at the end of the parameter declaration
6 ๏ธโƒฃ. At most one variable number of parameters can be declared at the parameter position of a method

๐Ÿ‘ป For instance:

class TestOverload{
    public void test(String[] msg){
        System.out.println("With string array parameters test Method ");
    }
    public void test1(String ... books){
        System.out.println("****Variable parameter length test1 Method****");
    }
    public void test1(String book){
        System.out.println("****Overloaded with deformable parameter methods test1 Method****");
    }
}

public class Methods for Variable Number of Parameters {
    public static void main(String[] args){
        TestOverload to = new TestOverload();
        to.test(new String[]{"aa"});//The first test method will be executed
        to.test1("aa" , "bb");//The first test1 method will be executed below
        to.test1("a");//The second test1 method will be executed below
        to.test1();//The first test1 method will be executed below
    }
}

๐Ÿ™‰ The second and fourth outputs of the final output call the method of the variable parameter. That is, the number of variable parameters ranges from [0, +].

๐Ÿ˜ธ Here, we can see that when a variable number of parameter methods of type String are defined in a class, there is no longer a method with the same name as a String array, which does not constitute an overload, because they are essentially the same in the compiler's view. That is, they cannot coexist


โญ Value transfer mechanism for method parameters

๐Ÿ’Ž A method must be called by its class or object to make sense. If the method contains parameters:
_formal parameter: parameter when method is declared
_Argument: The parameter value that is actually passed to the parameter when the method is called

โ“ How do Java arguments get passed into the method?
There is only one way to pass parameters to a method in Java: by value. A copy of the actual parameter value is passed into the method without affecting the parameter itself.
_Parameters are basic data types: pass the "data value" of the argument basic data type variable to the parameter
A_parameter is a reference data type: passing the "address value" of an argument referencing a data type variable to the parameter

โญ Parameter Transfer of Method

๐Ÿ’Ž Parameter transfer of basic data types

public static void main(String[] args) {
	int x = 5;
	System.out.println("Before modification x = " + x);// 5
	change(x);// x is an argument
	System.out.println("After modification x = " + x);// 5
	}
public static void change(int x) {
	System.out.println("change:Before modification x = " + x);
	x = 3;
	System.out.println("change:After modification x = " + x);
}


๐Ÿ’Ž Parameter Passing Referencing Data Types

public static void main(String[] args) {
	Person obj = new Person();
	obj.age = 5;
	System.out.println("Before modification age = " + obj.age);// 5
	// x is an argument
	change(obj);
	System.out.println("After modification age = " + obj.age);// 3
}
public static void change(Person obj) {
	System.out.println("change:Before modification age = " + obj.age);
	obj.age = 3;
	System.out.println("change:After modification age = " + obj.age);
}

class Person{
	int age;
}


๐Ÿ’Ž Parameter Passing Referencing Data Types

public static void main(String[] args) {
	Person obj = new Person();
	obj.age = 5;
	System.out.println("Before modification age = " + obj.age);// 5
	// x is an argument
	change(obj);
	System.out.println("After modification age = " + obj.age);// 5
}
public static void change(Person obj) {
	obj = new Person();
	System.out.println("change:Before modification age = " + obj.age);
	obj.age = 3;
	System.out.println("change:After modification age = " + obj.age);
}

class Person{
	int age;
}

๐Ÿ’™ Recursion of methods

๐Ÿ’Ž Recursive method: A method body calls itself.

1 ๏ธโƒฃ. Method recursion contains an implicit loop that repeats a piece of code, but this repetition persists
Rows do not require circular control.
2 ๏ธโƒฃ Recursion must recurse in a known direction, otherwise it becomes infinite, like death
loop

โญ Rewrite of method

๐ŸŒ€ Definition:

_In a subclass, if a method with the same name, return value type, and parameter list as the parent class is created, only the implementation in the body of the method is different in order to achieve different functions from the parent class, this method is called method override, also known as method override.
Method overrides are required when methods in the parent cannot meet the needs of the subclass or when the subclass has specific functionality.

_Since method rewriting must be based on inheritance, method rewriting will be explained in the next article on inheritance mechanisms

๐Ÿ’™ Summary

๐ŸŒŸ 3. Constructors

๐Ÿšฉ All classes have constructors, which are the key to distinguishing between classes and interfaces.
๐Ÿ”บ The construction method is a special method that is called automatically when instantiating a new object with the new keyword to complete the initialization operation
_new execution process:
_1 ๏ธโƒฃ Allocate memory space for objects
_2 ๏ธโƒฃ Call object construction method

๐Ÿ’™ Grammar Format:

Modifier class name (parameter list) {
_Initialization statement;
}

โญ Characteristics of the constructor

1 ๏ธโƒฃ It has the same name as the class
2 ๏ธโƒฃ It does not declare a return value type. (unlike declaring void)
3 ๏ธโƒฃ Cannot be modified by static, final, synchronized, abstract, native, and cannot have return statement return values
4 ๏ธโƒฃ There must be at least one construction method in each class (a parameterless construction is automatically generated if it is not explicitly defined)

๐Ÿ’™ The role of constructors

๐Ÿ’Ž Constructor works as 1 ๏ธโƒฃ Create Object 2 ๏ธโƒฃ Initialize Objects

๐Ÿ’™ Constructor Overload

1 ๏ธโƒฃ Constructors are typically used to create objects while initializing them.
2 ๏ธโƒฃ Constructor overloading makes object creation more flexible and easy to create a variety of different objects.
3 ๏ธโƒฃ Constructor overload, parameter list must be different
Example:

public class Person { //Constructor overload example
	private String name;
	private int age;
	private Date birthDate;
	public Person(String n, int a, Date d) {
	name = n;
	age = a;
	birthDate = d;
}
public Person(String n, int a) {
	name = n;
	age = a;
}
public Person(String n, Date d) {
	name = n;
	birthDate = d;
}
public Person(String n) {
	name = n;
	age = 30;
	}
}

Matters needing attention:
1 ๏ธโƒฃ If no constructor is provided in the class, the compiler generates a constructor without parameters by default
2 ๏ธโƒฃ If a construction method is defined in the class, the default parameterless construction will no longer be generated.
3 ๏ธโƒฃ The construction method supports overloading. Rule overload is consistent with common method overload

Code example:

class Person {
	private String name;//Instance member variable
	private int age;
	private String sex;
	//Default constructor constructor object
	public Person() {
		this.name = "caocao";
		this.age = 10;
		this.sex = "male";
}
	//Constructor with 3 parameters
	public Person(String name,int age,String sex) {
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	public void show(){
		System.out.println("name: "+name+" age: "+age+" sex: "+sex);
	}
}
public class Main{
	public static void main(String[] args) {
		Person p1 = new Person();//Call a constructor without parameters If the program does not provide a constructor without parameters
		p1.show();
		Person p2 = new Person("zhangfei",80,"male");//Call a constructor with three parameters
		p2.show();
	}
}

The "this" keyword used in the above code design constructor will be explained later when other keywords are introduced

๐Ÿ’™ Summary

โ›ฝ Attribute assignment process:

So far, we have talked about many places where attributes of classes can be assigned values. These locations are summarized and the order of assignments is indicated.

_Position of assignment:
_1 Default initialization
_2 Explicit initialization
Initialization in the constructor
_________8595
Initialize in static code block
_Order of assignments:
โ€ƒโ€ƒโ‘ค - โ‘  - โ‘ก - โ‘ข - โ‘ฃ

๐ŸŒŸ 4. Code Block

Fields are initialized in the following ways:

  1. In-place Initialization
  2. Initialize using a construction method
  3. Initialization using code blocks

You've learned the first two before, and now we'll look at the third, initializing with code blocks

๐Ÿ’™ What is a code block

๐Ÿ’Ž A piece of code defined with {}.
๐Ÿ”ฅ Static Code Block Execution First
_If multiple static or non-static code blocks are defined, they are executed in the order defined;

๐Ÿ’™ classification

Depending on where the code block is defined and the keyword, it can be divided into the following four types:
Common Code Block
_Block
_Static block
Synchronize Code Blocks (discussed in the Multithreaded section later)

๐ŸŒ€ Construction block

๐Ÿ’Ž Constructor: A block of code (without modifiers) defined in a class. Also called: Instance code block.
๐Ÿ”ฎ Role: Typically used to initialize instance member variables.

Example:

class Person{
	private String name;//Instance member variable
	private int age;
	private String sex;
	public Person() {
		System.out.println("I am Person init()!");
	}
	//Instance Code Block
	{
	this.name = "bit";
	this.age = 12;
	this.sex = "man";
	System.out.println("I am instance init()!");
	}
	public void show(){
			System.out.println("name: "+name+" age: "+age+" sex: "+sex);
	}
}
public class Main {
	public static void main(String[] args) {
	Person p1 = new Person();
	p1.show();
	}
}

๐ŸŒ€ Static Code Block

๐Ÿ’Ž Code block defined using static. Typically used to initialize static member properties.
๐Ÿ”ฎ Role: Initialize loading information for classes

๐ŸŒฑ Characteristic
1 ๏ธโƒฃ Static code blocks execute only once, and are the first to execute, regardless of how many objects are generated.
2 ๏ธโƒฃ When the static code block is executed, the instance code block (the constructor block) executes, followed by the constructor execution
3 ๏ธโƒฃ Internally, only static properties and methods in the current class can be invoked. Non-static properties, methods cannot be invoked

Example:

class Person{
    private String name;//Instance member variable
    private int age;
    private String sex;
    private static int count = 0;//Static member variables share data method area by class
    public Person(){
        System.out.println("I am Person init()!");
    }
        //Instance Code Block
    {
    this.name = "bit";
    this.age = 12;
    this.sex = "man";
    System.out.println("I am instance init()!");
    }
    //Static Code Block
    static {
        count = 10;//Only static data members can be accessed
        System.out.println("I am static init()!");
    }
    public void show(){
        System.out.println("name: "+name+" age: "+age+" sex: "+sex);
    }
}
public class Classes and Objects {
    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Person();//Will static code blocks still be executed?
    }
}

๐ŸŒ€ Non-static code block

๐Ÿ’Ž Common Code Blocks: Code blocks defined in methods
๐Ÿ”ฎ Role: Attribute information used to initialize the object;

๐ŸŒฑ Characteristic
1 ๏ธโƒฃ Executes as the object is created;
2 ๏ธโƒฃ You can call methods and properties of the current class
3 ๏ธโƒฃ Executes every time an object is created

public class Classes and Objects {
    public static void main(String[] args) {
        { //Define directly using {}, common method block
            int x = 10 ;
            System.out.println("x1 = " +x);
        }
        int x = 100 ;
        System.out.println("x2 = " +x);
    }
}

๐Ÿ’™ Summary

๐ŸŒŸ 5. Internal Classes

๐Ÿ’™ What is an internal class

๐Ÿ”Ž In Java, the definition of one class is allowed to reside inside another class, which is called an internal class and an external class.
Inner class is generally used within a class or statement block that defines it and must be given a full name when it is referenced externally.
Inner class cannot have the same name as the external class that contains it;

๐Ÿ’™ Internal Class Classification

Classification: 1 ๏ธโƒฃ Member internal class (static member internal class and non-static member internal class)
2 ๏ธโƒฃ Local inner class (without modifiers)
3 ๏ธโƒฃ Anonymous Inner Class

๐ŸŒ€ Member Inner Class

๐Ÿ’Ž A member internal class can exist as either a member of a class or a member internal class as a class:

โ„๏ธ Roles as members of classes

Unlike external classes, Inner class es can also be declared private or protected;
1 ๏ธโƒฃ The structure of an external class can be invoked
2 ๏ธโƒฃ Inner class can be declared static, but at this point you can no longer use non-static member variables of outer classes

Example:

class Outer {
	private int s;
	public class Inner {
		public void mb() {
			s = 100;
			System.out.println("Internal Class Inner in s=" + s);
		}
	}
	public void ma() {
		Inner i = new Inner();
		i.mb();
	}
}
public class InnerTest {
	public static void main(String args[]) {
		Outer o = new Outer();
		o.ma();
	}
}

โ„๏ธ Roles as classes

Structures such as attributes, methods, constructors can be defined internally
1 ๏ธโƒฃ Can be declared abstract class, so it can be inherited by other internal classes
2 ๏ธโƒฃ Can be declared final
3 ๏ธโƒฃ Build after compilation O u t e r C l a s s OuterClass OuterClassInnerClass.class$byte code file (also applicable to local internal classes)

Example:

public class Outer {
	private int s = 111;
	public class Inner {
		private int s = 222;
		public void mb(int s) {
			System.out.println(s); // Local variable s
			System.out.println(this.s); // Properties of Internal Class Objects
			System.out.println(Outer.this.s); // External Class Object Properties s
	}
}
public static void main(String args[]) {
		Outer a = new Outer();
		Outer.Inner b = a.new Inner();
		b.mb(333);
	}
}

โ— NOTE

1 ๏ธโƒฃ. Members in internal classes of non-static members cannot be declared as static. Static members can only be declared in external classes or internal classes of static members.
2 ๏ธโƒฃ. External classes access members of member internal classes in a way that requires either Internal Class. Members or Internal Class Objects. Members
3 ๏ธโƒฃ. A member internal class can directly use all members of an external class, including private data
4 ๏ธโƒฃ. Consider declaring an internal class static when you want to use it in the static member part of an external class

๐ŸŒ€ Local Internal Class

โ„๏ธ Declare local internal classes

class External Class{
		Method(){
		class Local Internal Class{
		}
	} 
	{
		class Local Internal Class{
		}
	}
}

โ„๏ธ Use local internal classes

๐Ÿ’Ž It can only be used in methods or code blocks that declare it, and it is declared before it is used. This class cannot be used anywhere else
_However, its object can be returned for use through the return value of an external method, and the return value type can only be the parent or interface type of a local internal class

โ„๏ธ Features of local internal classes

1 ๏ธโƒฃ Internal classes are still separate classes and will be compiled into separate classes after compilation. class file, but
Is the class name and $symbol of the external class preceded by the number.
2 ๏ธโƒฃ It can only be used in methods or code blocks that declare it, and it is declared before it is used. Anywhere else
None of them can use this class.
3 ๏ธโƒฃ Local internal classes can use members of external classes, including private ones.
4 ๏ธโƒฃ Local internal classes can use local variables of external methods, but must be final. By local internal classes and bureaus
Different periods of declaration of partial variables.
5 ๏ธโƒฃ Local internal classes and local variables are in the same position as public,protected, and private by default.
6 ๏ธโƒฃ Local internal classes cannot be decorated with static and therefore cannot contain static members

๐ŸŒ€ Anonymous Inner Class

๐Ÿ’Ž Anonymous internal classes cannot define any static members, methods, and classes, only one instance of an anonymous internal class can be created.
_An anonymous internal class must be behind new, implying an interface or implementing a class.

โ„๏ธ Declare an anonymous internal class

new Parent Constructor (Argument List) |Implement Interface(){
	//Class body part of an anonymous inner class
}

โ„๏ธ Features of anonymous internal classes

1 ๏ธโƒฃ Anonymous internal class must inherit parent class or implement interface
2 ๏ธโƒฃ Anonymous inner class can have only one object
3 ๏ธโƒฃ Anonymous internal class objects can only be referenced in polymorphic form

๐Ÿ’™ Summary

This article mainly introduces classes and class members, some of which will involve the following inheritance, keywords and other knowledge, which will be explained in the subsequent updates of the blog, but also please continue to pay attention.
If there are any errors in this article, please also point them out in the comments section, thank you

Tags: Java

Posted by fingerprn on Sat, 16 Apr 2022 02:02:27 +0930