Section 1 Object orientation

Classes and objects

The concept of classes and objects

A class is a class of things that have the same properties and behavior. And an object is an actual entity that actually exists in a class. For example, an animal is a class, and a dog is a single individual belonging to an animal, that is, an object. In Java, the syntax for instantiating an object from a class is as follows:

Class name object =newThe name of the class (); Example: Student stu =new Student();
Copy the code

Member properties and member methods

Member methods are non-static methods defined in a class. They are called member methods (there is a distinction between ordinary and static methods, described below). A member attribute is a non-static attribute defined inside a class and outside of a method. It is called a member variable or global variable. The structure of member methods is as follows:

Data type function name ([argument list]){code to implement the method; [returnVariable or value]; } such as:public String getStudentName(int StudentId) {
    String studentName = null;
    if (StudentId == 1) {
        studentName = "Zhang";
    }
    return studentName;
}
Copy the code

The relationship between classes and objects has the following three points:

  • Any object created from a class has all the attributes and methods of that class
  • A class can create an infinite number of objects
  • Class member properties and methods must be called through the object

Local variables and global variables

Member variables are global variables, while local variables are variables declared in methods. You cannot have two identical global variables in the same class; You cannot have two identical local variables in the same method; However, the same global variable and local variable can exist in the same class, and will be used in accordance with the nearby principle, that is, the statement using the variable will use the variable which is close to the variable, for example:

// Member variables
public int a = 1;
// Member methods
public void print(a) {
    system.out.println("The value of a is: + a); // The value of a is 1 because the output statement is close to the member variable
    int a = 2;
    system.out.println("The value of a is: + a); // The value of a is 2 because the output statement is close to the local variable
}
Copy the code

Member method overloading

The phenomenon of having the same method name and different argument lists in the same class is method overloading. There are three cases of different parameter lists:

  • The number of parameters is different
  • Parameters have different data types
  • Parameters have different data type orders

Create object memory analysis

  • Stack memory: Methods are pushed onto the stack as they are executed and destroyed when they are finished.
  • Heap memory: Each time an object is instantiated, a chunk of heap memory is created that contains all the member variables and member methods of the corresponding class, and the member variables have default values.
  • Method, when executed, pushes the object of the operation onto the stack, which is actually a reference to an address in heap memory. In Java, an object in stack memory can only point to an address in heap memory, and an address in heap memory can be pointed to by objects in multiple stacks at the same time.

Value passing and reference passing

In Java, = stands for assignment, which is assigning a value to a variable. Assignment is divided into two kinds, one is value pass, one is reference pass; Assignment to a primitive data type is value passing, that is, assigning a value directly to a variable. For class and array types, it is reference-passing, assigning the address of the reference type to the variable when the reference type is assigned. Such as:

int a = 1;
int b = a; // Assign a value of 1 to b, where b is 1.
Student stu1 = new Student("Xiao Ming"."Male"); // For STU1, it holds a reference to the Student(" kid "," boy ") object in the heap, not the object itself.
Student stu2 = stu1; // Assign a reference to stu1 to stu2. Both stu1 and STU2 refer to the same object.
Copy the code

Static modifier

The static keyword can be used to modify member methods and attributes. The modified methods and attributes are initialized when the class is loaded, so they can be called using the class name without creating an object. Method name or class name. Property name to make the call. In a static member method, you cannot call a non-static member method or a non-static member attribute directly, because the static member method has priority with the object. At this time, the non-static member method and the non-static member attribute have not been initialized, and the call error will occur.

2. Enclosed

Concept of encapsulation

Encapsulation refers to the process of writing code to hide the implementation details of the code from the outside. It refers to the provision of common access or methods to manipulate its internal details or attributes. The purpose of encapsulation is to secure properties and data.

An implementation encapsulated in Java

In Java, encapsulation is implemented mainly through several keywords, which can be achieved by adding several keywords in front of a class or method or property. These keywords are also called access modifiers, as follows:

  • Public: public. The maximum access permission is available to all classes.
  • Protected: protected. Subclasses under different packages can be used;
  • Default: do not write any access modifier is the default modifier, different packages are not available;
  • Private: Only you can use it.

Due to the characteristics of, a special class is generated, in which there are usually only member attributes and their corresponding GET /set methods. This class is called blood loss model, for example:

public class Person{
    // Member variables
    private int age;
    // Member methods
    public void setAge(int a){
        age = a;
    }
    public int getAge(a){
        returnage; }}Copy the code

For a member variable, we usually write the parameter in the corresponding set method with the same name as the parameter. However, there is a problem here. The set method assigns the value of the parameter to the member variable, but how do we determine which one is assigned to whom if it has the same name? At this point, another keyword is needed. This keyword is called this, which refers to the object that is currently calling the property or method. Therefore, it can be used to distinguish member variables from local variables. The one with this is the member variable, so the above blood loss model can be written as follows after optimization:

public class Person{
    // Member variables
    private int age;
    // Member methods
    public void setAge(int age) {
        this.age = age;
    }
    public int getAge(a){
        return this.age; }}Copy the code

Constructor and constructor code block

Inside a class there is a special method that returns no value and has the same name as the class. This method is called a constructor, as follows:

public class Student {
    private int a = 1;
    // constructor
    public Student(a) {}
    // Construct the code block{}}Copy the code

The corresponding constructor is called each time an object is created. Constructor can not write, Java will provide default at compile time, no arguments constructor, however, if you manually add a constructor (no arguments or ginseng), Java will no longer provide default, no arguments constructor when manually added a constructor refs so, no structure will not be provided, if you need to use, You have to add it manually. The construction code block is executed before the constructor, and each time the constructor is called, the code in the construction code block is executed before the code in the constructor is executed.

3. Inheritance

The concept of inheritance

The extends keyword is inherited in Java as follows:

public class Person {
    public int age;
}
public class Student extends Person {
    public String name;
}
Copy the code

By inheriting, a subclass owns all the attributes and methods of its parent class, as in the example above, Student owns the age attribute of its parent class. Subclasses can also have their own attributes and methods, such as the name attribute, which is the Student attribute. Thus, the main purpose of inheritance is code reuse and extension. The main characteristics of inheritance are as follows:

  • A subclass owns all the attributes and methods of its parent class (including private attributes and methods), but the private attributes and methods of its parent class are not directly accessible. In fact, this is related to the principle of inheritance, the subclass inherits the parent class, when creating the object of the subclass, will first initialize the object of the parent class in the open space, and then initialize the child class, the subclass holds the parent class, all subclasses can directly call the methods of the parent class, but the private attributes and methods of the parent class, Methods extended by subclasses cannot be called, but can only be called by their parent class’s ordinary methods (” inherited “methods), as shown in the following figure:

  • A subclass can have its own attributes and methods, that is, a subclass can extend its parent class.
  • Subclasses can implement the methods of their parent class in their own way.

The super keyword

In the first line of each constructor, the default is super(), which calls the constructor of the parent class. If super() is not written, Java will default to super() at compile time and call the constructor of the parent class with no arguments. Super is essentially an object that refers to a superclass object. So you can use super in a subclass to call methods of a parent class, and super is only available in a subclass if it inherits an inheritance relationship.

Methods to rewrite

In an inheritance relationship, a subclass has exactly the same methods as its parent class. This is called overwriting. If a subclass overrides a method of its parent class, then after creating a subclass object, the subclass object calls the overridden method of its own class.

  1. Purpose of rewriting: The main purpose of rewriting is that if some method in the parent class needs to be called, but the effect of the implementation is not the desired effect of the child class, then the child class defines a method that is the same as the parent class, and implements its own code.
  2. The difference between overwriting and overloading: Overwriting occurs in an inheritance or implementation relationship. A subclass overrides the methods of its parent class. The methods of the subclass must be the same as the methods of the parent class except for the method body. Overloading is in the same class, with the same function name, different parameter types.

abstract

In Java, abstractions can have abstract classes or methods.

  1. By adding the abstract keyword in front of the class, it becomes abstract. Abstract classes are used to regulate the behavior of subclasses. If a subclass inherits an abstract class, it must override all the abstract methods in the abstract class or make itself an abstract class. Abstract classes have constructors, but cannot be new objects; And there can be ordinary member methods and member variables in the abstract class. Because new objects are not possible, ordinary member methods and member variables in the abstract class can only be called through their subclass objects.
  2. By prefixing the method with the Abstract keyword and leaving the topic of the method unwritten, the method becomes an abstract method. If a class has abstract methods, that class must also become abstract.

4. Polymorphism

interface

In addition to ordinary classes, abstract classes have a special type in Java called interfaces. The interface is declared using the interface keyword. It has the following characteristics:

  • An interface can only implement a relationship with a class, which is implemented using the implements keyword.
  • Methods in the interface are abstract methods, all methods can not exist in the method body, and the default add abstract keyword, can be omitted;
  • A class can implement more than one interface at a time, and if more than one interface is implemented, the subclass must override all methods in all interfaces.
  • There are no constructors in the interface, so you can’t get an object (unlike an abstract class, whose constructors are called when an abstract class creates its subclass object, which gets the object and is held by the subclass object, so that the subclass object can call the ordinary member methods and member variables in the abstract class);
  • An interface can have variables that are modified by the fianL keyword and cannot be modified once assigned.

The final keyword

The final keyword in Java can be used to modify classes, variables, and methods.

  • Final modifies classes, which are called final classes and can no longer be inherited;
  • Final modifies variables. The modified variable can be assigned once, either at the time of the declaration or after the declaration, but once assigned, it cannot be modified.
  • The final modifier cannot be overridden, which is also known as the final method. Therefore, the final and abstract keyword cannot be used together because the two methods must be overridden, and the other method cannot be overridden.

The concept of polymorphism

Polymorphism is the multiple forms of a thing, represented in Java as a declaration of a parent class pointing to an instance of a child class, as shown below:

The parent class declares the variable name =newSubclass instance (); Animal animal =new Cat();
Copy the code

The above form is also called upcast, that is, the instance of the subclass is converted to the parent class object; Since there is an upward transformation, there must also be a downward transformation. Downward transformation means that the parent object is transformed into a subclass object, provided that the parent object itself is transformed from the subclass object upward, as shown below:

Animal animal = new Cat();    // If the object is an instance of a subclass, the downward transition will be successfulThe declared variable name of the subclass = (subclass name) object; Cat c = (Cat)animal;Copy the code

So in the polymorphic case, if I have an object that’s a declaration of a superclass that points to an instance of a subclass, and when I call a method on that object, if I’m calling a property or a method, that property or method exists in either the parent or the subclass, whose method am I calling? Here comes another concept, called dynamic binding, which is based on four main principles

  • When this object calls a normal member method, it looks left at compile time and right at run time.
  • When the object calls a static member method, compile to the left and run to the left;
  • When this object calls a normal member variable, compile to the left and run to the left;
  • When this object calls a static member variable, compile to the left and run to the left.

Anonymous objects

In actual code, some objects may be used only once and are no longer needed. At this time, it is not necessary to write all the code of the new object. Anonymous objects can be directly used to save the complicated code writing.

public class Cat{
    public String color="Orange cat";
}
public class Test{
	public static void main(String[] args){
        new Cat();// Anonymous objects
        System.out.println(newCat().color); }}Copy the code

The inner class

Classes defined inside other classes are called inner classes. Classes that contain inner classes are called outer classes. The inner class can directly access the member variables of the outer class, including a private; An external class must first create an object if it wants to access an inner class’s member variables. According to the position of inner class in the outer class, inner class is divided into two types, namely member inner class and local inner class.

  • Member inner class
Sample code:class Outer {
    // Member variables
    private int num = 10;
    // Member inner class
    class Inner {
        public void show(a) { System.out.println(num); }}}Copy the code

The syntax for member inner classes to create objects is: external class name. Inner class name Object name = new Outer class ().new inner class (); If a member inner class is decorated with private, the inner class cannot create objects outside the outer class. If the static keyword is used to decorate the member inner class, then the object of the inner class can be fetched directly from the outer class. Inner class object name = new Outer class. The inner class () must also be static if it needs to access other member properties of the inner class. If it needs to access static properties or methods of the inner class, it can access static properties of the inner class through the outer class. Inner class. Properties/methods ();

// Sample code
class Outer {
    private int num = 10;
    private static int num2 = 100;
    Inner classes are statically decorated because inner classes can be treated as members of outer classes
    public static class Inner { // Inner class is static inner class
        public void show(a) {
            // System.out.println(num); Cannot be accessed because num is non-static
            System.out.println(num2);
        }
        public static void show2(a) {// Static methods in a static inner classSystem.out.println(num2); }}}class InnerClassDemo {
    public static void main(String[] args) {
        Outer.Inner oi = new Outer.Inner();
        oi.show();
        oi.show2();
        // Another way to call show2()Outer.Inner.show2(); }}Copy the code
  • Local inner class

Method defined in the internal class called local inner classes, local inner classes only can be used inside the definition of method, and the local inner classes if you need to access methods defined in the local variables, so this variable must be final modification, the aim is to prevent anonymous inner classes in the use of this variable, Due to changes in external local variables, results are inconsistent with expectations or even abnormal. After final modification is used, external local commands can no longer be changed, thus ensuring consistency of results.

// Define the class at the local location
class Outer {
    private int num  = 10;
    public void method(a) {
        int num = 20;
        // final int num2 = 20;
        class Inner {The inner class is defined inside the method and is a local inner class
            public void show(a) {
                // System.out.println(num); The local variable num cannot be accessed because num may not even exist.
                // Access the local variable num2 from the inner class; Need to be declared as final type
                System.out.println(num2);/ / 20}}//System.out.println(num2);
        Inner i = new Inner();// The local location can new the object of the inner class and call the methodi.show(); }}Copy the code
  • Anonymous inner class

An anonymous inner class is a type of local inner class that is essentially an anonymous object that inherits the class or subclasses that implement the interface. The usage method is as follows:

Prerequisite: There is a class or interface format:newClass name or interface name (){override method; } The essence of an anonymous inner class: an anonymous object that inherits the class or subclasses that implement the interface// An example of an anonymous inner class that prints "HelloWorld" in the console
interface Inter{
    void show(a);
}
class Outer{
    public staitc Inter method(a){
        return new Inter(){
        	public void show(a){
                System.out.println("HelloWorld"); }}}}class OuterDemo{
    public static void main(String[] args){ Outer.method().show(); }}Copy the code