๐ 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>();
- A class is simply a model-like thing that defines what members it has.
- 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 value | Has Return Value | |
---|---|---|
Invisible parameter | void method name (){} | Type method name () {} of return value |
Tangible parameters | void 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:
- In-place Initialization
- Initialize using a construction method
- 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