Object oriented (I)
Object oriented overview
Object oriented programming is a programming idea in line with human thinking habits. There are various forms of things in real life, and there are various connections between these things. In the program, objects are used to map things in real life, and the relationship between objects is used to describe the relationship between things. This idea is called object-oriented
The characteristics of object - oriented can be summarized as encapsulation, inheritance and polymorphism
- encapsulation
Encapsulation is the core idea of object-oriented, which encapsulates the attributes and behaviors of objects without letting the outside world know the specific implementation details
- inherit
Inheritance mainly describes the relationship between classes. Through inheritance, the functions of the original class can be extended without writing the original class
- polymorphic
Polymorphism refers to a variety of different behavior characteristics when a subclass object is directly assigned to a parent class reference variable and variables of the same reference type call the same method after the attributes and functions defined in a class are inherited by other classes. For example, when you hear the word cut, the barber's behavior is to cut his hair, while the actor's behavior is to stop performing
Classes and objects in Java
The idea of object - oriented programming tries to keep the description of things in the program consistent with the form of the transaction in reality
Relationship between class and object
A class is an abstract description of a class of things, and an object is used to represent the individual of such things in reality
Class definition
To create an object in a program, you first need to define a class
With the idea of object-oriented programming, we can encapsulate the common features and behaviors in a class, take the common features as class attributes (also known as member variables), and take the common behaviors as class methods (also known as member methods)
- Class definition format
Classes in Java are defined through the class keyword, and their syntax format is as follows:
[modifier] class name [extensions parent class name] [implement ation interface name]{
//Class body, including member variables and member methods of the class
}
The modifier can be written or not (default); the class name should conform to the naming specification of the identifier; extensions is used to describe which parent class the defined class inherits from; implements keyword is used to describe which interfaces the current class implements, which will be described later and will not be repeated here
- Declare (define) member variables
The member variable of a class is also called the attribute of a class. It is mainly used to describe the characteristics of an object. The syntax format of declaring member variables is as follows:
[modifier] data type variable name [= value];
The modifier is optional and is used to specify the access permission of the variable; the data type can be any type in Java; the variable name is the name of the variable and must comply with the naming rules of the identifier; the variable can be assigned or not assigned, the unassigned variable is called the declaration variable, and the assigned variable is called the definition variable
- Declare (define) member methods
Member methods are also called methods, similar to functions in C language. They are mainly used to describe the behavior of objects. The syntax format of methods is as follows:
[modifier] [return value type] method name ([parameter type parameter name 1], [parameter type parameter name 2],...){
//Method body
...
Return return value; / / the return value type is void. The return value type and its return value can be ignored
}
In the above syntax format, [] means optional, and the explanation of each part is as follows:
- Modifier: defines the access rights (e.g. public,protected,private); static modifier; final modifier;
- Return value type: defines the data type of the return value of the calling method. When the return value is not required, the void keyword can be used
- Parameter type: defines the data type of the parameter passed in when calling the method
- Parameter name: it is a variable that receives the data passed in when calling the method
- Return: used to end the method and return the value of the type specified by the method. When the return type is void, return and its return value can be ignored
- Return value: the value returned by return, which will be returned to the caller
// Define a Person class public class Person { String name; //Unassigned member variable, declared variable int age = 0; //The assigned member variable defines the variable void speak() { // Member method, return type is void System.out.println("My name is" +name +"I this year" +age +"year!"); } }
Creation and use of objects
In Java programs, you can use the new keyword to create objects. The specific syntax format is as follows:
Class name object name = new class name ();
For example:
Person me = new Person();
The essence of the new object is to apply for memory space from the heap
There are two kinds of memory in Java: stack memory and heap memory. Stack memory is used to store basic type variables, and heap memory is used to store objects and arrays created by new
The variable me of Person type is stored in the stack memory, which is a reference and will point to the real object; the object created through new Person() is stored in the heap memory, which is the real object
Access all members of the object through the reference of the object. The syntax format is as follows:
Object references. Object members
public class Example02 { public static void main(String[] args) { Person p1 = new Person(); //Create the first Person object Person p2 = new Person(); //Create a second Person object p1.age = 18; //Access the member variable age of object p1 and assign a value p1.speak(); //Access the member method speak() of object p1 p2.speak(); //Access the member method speak() of object p2 } }
In addition to object reference to access object members, you can directly use the created object itself to reference object members. The specific format is as follows:
new class name (). Object member
This method accesses a member of the object while creating the instance object through the new keyword, and only one of the members can be accessed after creation. Because there is no object reference, after accessing an object member, the object will become a garbage object
When instantiating an object, the Java virtual opportunity automatically initializes the member variables and assigns different initial values to different types of member variables, as shown in the following table
Member variable type | Initial value | Member variable type | Initial value |
---|---|---|---|
byte | 0 | double | 0.0 |
short | 0 | char | Empty character '\ u0000' |
int | 0 | boolean | false |
long | 0 | Reference data type | null |
float | 0.0 |
Access control character
In Java, there are four access levels for classes, member methods and attributes, which are private,default,protected and public
The following figure lists the four control levels from small to large:
- private
Current class access level: if a member of a class is decorated with a private access modifier, the class can only be accessed by other members of the class, and other classes cannot access it directly - default
Package access level: if a class or its members are not decorated with any modifiers, it is the default access control level (package private), which can only be accessed by other classes in the package - protected
Subclass access level: if a member of a class is modified by a protected access control character, the member can be accessed by other classes in the same package or subclasses of the class in different packages - public
Public access level: this class or its members can be accessed by all classes
Access scope | private | default | protected | public |
---|---|---|---|---|
In the same category | ✔️ | ✔️ | ✔️ | ✔️ |
In the same bag | ✔️ | ✔️ | ✔️ | |
In subclass | ✔️ | ✔️ | ||
Global scope | ✔️ |
tips: if a public modifier class is defined in a source file, the file name of the source file must be the same as that of the public modifier class; If the class in the Java source file is not decorated with public, the file name of the Java source file can use any legal file name
Class encapsulation
Class encapsulation means that the state of an object is hidden inside the object, and external programs are not allowed to directly access the internal information of the object. Instead, operational access to internal messages is realized through the methods provided by the class
Encapsulation, that is, hiding the attributes and implementation details of the object, only exposing the interface, and controlling the access level of attribute reading and modification in the program
Why encapsulation
- Improve code reusability
- Improve code maintainability
- Solve the permission problem of data access
How to implement encapsulation
When defining a class, privatize the attributes in the class, that is, modify them with the private keyword. Private attributes can only be accessed in the class in which they are located. If the outside world wants to access private attributes, it is necessary to provide some public methods modified with public, including getXxx() method for obtaining attribute values and setXxx() method for setting attribute values
class Person{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if(age <= 0) System.out.println("The age you entered is incorrect!"); else this.age = age; } public void speak() { System.out.println("My name is" +name +"this year" +age +"year!"); } } public class Example04{ public static void main(String[] args){ Person p = new Person(); p.setName("Zhang San"); p.setAge(-18); p.speak(); } }
Method overloading and recursion
Method overload
Java allows you to define multiple methods with the same name but different types or numbers of parameters in a program, which is method overloading (needs to be in a class)
Method overloading must meet three conditions:
- Methods must be in the same class
- Method names must be the same
- Methods have different formal parameter lists
*Note: method overloading is independent of the return value type
public class Example06 { public static void main(String[] args) { int sum1 = add(1, 2); int sum2 = add(1, 2, 3); double sum3 = add(0.2, 5.3); System.out.println("sum1=" +sum1); System.out.println("sum2=" +sum2); System.out.println("sum3=" +sum3); } public static int add(int num1, int num2) { return num1 + num2; } public static int add(int num1, int num2, int num3) { return num1 + num2 + num3; } public static double add(double num1, double num2) { return num1 + num2; } }
Recursion of method
Method recursion refers to the process of calling itself inside a method
Recursion must have an end condition, otherwise it will fall into the state of infinite recursion and will never end the call
Recursion consumes a lot of stack memory
public class Example07 { public static void main(String[] args) { int sum = getSum(4); //Call the recursive method to get the sum of 1-4 System.out.println)("sum=" +sum); } public static int getSum(int num) { if (num == 1){ return 1; } //If the conditions are met, the recursion ends int temp = getSum(n-1); return temp + num; } }
Construction method
Constructor is a special member of a class. It will be called automatically when the class instantiates an object, and it will assign values to the properties of the object at the same time of instantiating the object
Definition of construction method
The construction method needs to meet three conditions:
- The method name is the same as the class name
- No declaration of return value type
- You cannot use a return statement to return a value (you can use return as the end of the method)
*Without writing construction methods, the Java virtual machine will automatically add parameterless construction methods when compiling
[modifier] method name ([parameter list]){
Method body
}
class Person { public Person() { // Nonparametric construction method System.out.println("A parameterless constructor was called"); } } public class Example08 { public static void main(String[] args) { Person p = new Person(); //When instantiating a Person object through new Person(), the parameterless constructor of this class will be called automatically } }
class Person { int age; public Person(int num) { age = num; } //Parametric construction method public void speak() { System.out.println("I this year" +age +"year"); } } public class Example09{ public static void main(String[] args) { Person p = new Person(18); // Call the parameterized construction method, pass in the int parameter 18, and assign a value to the age attribute p.speak(); } }
Overloading of construction methods
Like ordinary methods, constructors can also be overloaded
Multiple constructors in a class (different parameter lists) are overloaded
public class Example10 { public static void main(String[] args) { Person p1 = new Person(18); Person p2 = new Person("Zhang San", 32); p1.speak(); p2.say(); } } class Person { String name; int age; public Person(){} //Default parameterless construction method public Person(int num) { age = num; } //Parametric construction method 1 public Person(String name, int age) { //Parametric construction method 2 this.name = name; this.age = age; } public void say() { System.out.println("My name is" +name +"this year" +age +"year"); } public void speak() { System.out.println("I this year" +age +"year"); } }
Each class in Java has at least one constructor. Although if the constructor is not explicitly defined, the virtual opportunity will automatically create a default constructor for this class, once the constructor is defined for this class, the system will not provide the default parameterless constructor
Therefore, if you define a construction method with parameters, you'd better define a construction method without parameters
this keyword
Java provides a keyword this to refer to the current object, which is used to access other members of the object in the method
Common usage of this:
- Call member variables through this keyword to solve the problem of name conflict with local variables
class Person { int age; // Member variable age public Person(int age) { // Incoming parameter - local variable age this.age = age; // Assign the value of the passed in parameter (local variable) age to the member variable age } }
- Calling member methods with the this keyword
class Person { public void speak() { System.out.println("speak!"); } public void say() { this.speak(); // Because speak() is in the same class, this here can be omitted without writing } }
- Call the constructor through the this keyword
class Person { public Person() { //Nonparametric construction method System.out.println("Nonparametric construction method"); } public Person(int age) { //Parametric construction method this(); //Call parameterless constructor // You can call other constructor methods in the form of "this([parameter 1, parameter 2,...])" in one constructor System.out.println("Parametric construction method"); } } public class Example11{ public static void main(String[] args){ Person p = new Person(18); //Instantiate the Person object } }
When using this to call the constructor of a class, you should pay attention to the following points:
- this can only be used in constructor to call other constructor methods, not in member methods
- In a construction method, the statement that uses this to call the construction method must be the first execution statement of the method and can only appear once
- You cannot call each other with this in two constructor methods of a class
static keyword
In Java, a static keyword is defined, which is used to modify the members of a class, such as member variables, member methods and code blocks
- Static class: static class School {...}
- Static variable: static int age;
- Static method: static void say() {...}
Static variable
Sometimes, developers want some specific data to exist only in memory and be shared by all instance objects of a class
static keyword can only be used to modify member variables, not local variables
Syntax for accessing static variables:
Class name. Variable name
class Student{ static String schoolName; //Declare static variable schoolName } public class Example12 { public static void main(String[] args){ Student stu1 = new Student(); Student stu2 = new Student(); Student.schoolName = "Tsinghua University"; //Assign values to static variables System.out.println("I am" +stu1.schoolName +"Students"); System.out.println("I am" +stu2.schoolName +"Students"); } }
Static method
You can call a method without creating an object
In a static method, only members decorated with static can be accessed. The reason is that members not decorated with static need to create objects before they can be accessed, while static methods can not create any objects when called
Syntax format for accessing static methods:
Class name. Method
perhaps
Instance object name. Method
class Person{ public static void say(){ System.out.println("Hello World!"); } } public class Example13{ public static void main(String[] args){ Person.say(); // Use "class name. Method name" to call static methods Person person = new Person(); // Instantiate object person.say(); // Use "instance object name. Method" to call static methods } }
Static code block
In Java, several lines of code enclosed by a pair of braces are called a code block, and the code block decorated with static is called a static code block
The syntax format of static code block is as follows:
static {
...
}
When the class is loaded, the static code block will be executed. Since the class is loaded only once, the static code block will be executed only once
In programs, static code blocks are often used to initialize class member variables
class Person{ static{ System.out.println("Yes Person Static code block in"); } } public class Example14 { static{ System.out.println("Yes Example14 Static code blocks in"); } public static void main(String[] args){ Person p1 = new Person(); Person p2 = new Person(); } }
Executed the static code block in Example14
Executed a static code block in Person
In the process of instantiating the object twice, the contents of the two static code blocks are output only once. The static code block in Example14 is executed when the class is loaded, while the static code block in Person is executed only once when the Person object is instantiated for the first time. The second instantiation object will not execute the static code block in Person
Code block
The syntax format of static code block is as follows:
static {
...
}
When the class is loaded, the static code block will be executed. Since the class is loaded only once, the static code block will be executed only once
In programs, static code blocks are often used to initialize class member variables
class Person{ static{ System.out.println("Yes Person Static code block in"); } } public class Example14 { static{ System.out.println("Yes Example14 Static code blocks in"); } public static void main(String[] args){ Person p1 = new Person(); Person p2 = new Person(); } }
Executed the static code block in Example14
Executed a static code block in Person
In the process of instantiating the object twice, the contents of the two static code blocks are output only once. The static code block in Example14 is executed when the class is loaded, while the static code block in Person is executed only once when the Person object is instantiated for the first time. The second instantiation object will not execute the static code block in Person