Chapter V object oriented

Finally, the key content is object-oriented
Here, object-oriented is an important content of Java development. We must master and have the idea of object-oriented programming in order to better create and develop excellent programs
Object oriented refers to the abstract description of a thing as an object, and the use of variables and methods to implement and build this thing
Three characteristics of object-oriented: inheritance, encapsulation and polymorphism

public class Demo{//class
    final String name = "XiaoMing";//Constant decorated member variable
    public Demo(){
        String demoName = "ZhangSan";//local variable
    };//Constructor has no parameters
    public void Info(){
        System.out.println("I am Demo Class output information method");
    }//Custom methods usually output information about the class itself
    public void Test(Demo demo){
        System.out.print("The test method called the information method:");
        demo.Info();
    }//Custom methods are often used to test code
    public Demo(int num){
        System.out.println("Parameters of the input constructor:"+num);
    };//Constructor has parameters
    public static void main(String[]args){
        Demo demo = new Demo(17);//Create an object instance and pass in parameters
        demo.Test(demo);//Call the Test method
    }
}

Let's look at the contents of the above code one by one
class

First, public class Demo {} is the class itself, and then the class keyword represents the class. There can only be one public java file, and it must be the same as the file name, in order to load the main class, call the main method, etc
constructor

public Demo() {} and public Demo(int num) {} are constructors
Constructor refers to the method called when the class is created, and it is also the first method to be called. Here, the constructor must exist. It inherits the Object class. Even if you don't write any form of constructor, there will be a parameterless constructor you can't see. Unless you define the constructor, there will be no automatically generated constructor
In the abstract, the variables and code inside the constructor are usually used to initialize operations. For example, the person you were born has age and gender. If you look at the object-oriented, these are the contents of the constructor, and most of the afterbirth things are determined by methods
Constructor writing method: Demo demo = new Demo(); new Demo(); It can be regarded as calling the constructor, and it is found that when creating an object, the constructor must call the calling method, which is a must
There are also many contents of constructor parameters, including polymorphism. Please see the following articles for details
method

public void Info(){} public void Test(Demo demo){}
The uplink code is the method
The method is used to enable the class object to perform some operations. The code is encapsulated in the method. The call is convenient for reuse and other operations. A meal can be performed many times. If it is written in the main method or other code block, it will be very troublesome to call again.
Method: demo.Info(); demo is the object we created. The method is called
Here, our method does not set parameters, and all empty parentheses can be used
Methods also have many related contents, including rewriting abstract class interfaces. Please see the following articles for details
Main method

The main method public static void main(String[]args) {} the main method is the entry of all program codes. The writing method of the execution method is fixed. The main method is also the stack principle. It can learn the data structure in detail later. In the early stage, just know what it is and how to use it
Member variables and local variables

Here, variables are divided into two classes: member variables and local variables
A member variable, also known as a global variable, is actually a member variable whose scope is in the whole program (if there is a modifier in its own class) and does not need to be assigned an initial value. A local variable is also called a temporary variable. Its scope is only in its own code block or curly braces. It can no longer be used outside its own scope, and will be recycled and destroyed by the garbage collector with code execution, Member variables will always be saved, and local variables must also be assigned initial values. When writing code, we suggest that unimportant variable data can use temporary variables, and the smaller the scope, the better, in order to reduce computer performance consumption and memory ratio. Although computer hardware technology is becoming stronger and stronger, However, excellent programs always use the least resources in exchange for the maximum operation and execution revenue and efficiency

public class Demo{
    static int ForNumber;
    public static void main(String[] args) {
        for(ForNumber=0;ForNumber<=10;ForNumber++){
            System.out.println("The first"+ForNumber+"Secondary cycle");
        }
        System.out.println("End of cycle");
    }
}
public class Demo{
    public static void main(String[] args) {
        int ForNumber;
        for(ForNumber=0;ForNumber<=10;ForNumber++){
            System.out.println("The first"+ForNumber+"Secondary cycle");
        }
        System.out.println("End of cycle");
    }
}
public class Demo{
    public static void main(String[] args) {
        for(int ForNumber=0;ForNumber<=10;ForNumber++){
            System.out.println("The first"+ForNumber+"Secondary cycle");
        }
        System.out.println("End of cycle");
    }
}

It can be found from the above three programs that the running results of the three programs are consistent, but the scope of the variable is getting smaller and smaller. If your circular variable has other uses and has very reserved value, it needs to be set as a member variable. If it is not very useful, but it will also be used, you can create a local variable in the method, If it is just a loop variable, it is only created and used within the for loop statement
You may think it's too much to deduct memory and other computer performance, but excellent programs are like this. Many algorithms can get the same answer for one thing, but some take 10 seconds, and some only take 1 second, which is also the saving of computer performance and the excellence of program algorithms
This is also the meaning of different usage scenarios of algorithms and variables

5.1 classes and objects

The syntax for defining a class is: define class name - > define constructor - > define member variable - > define method
The simplest class is to define only the class name. Although it is also a class, it has no meaning. Therefore, a class must have many contents and elements to be a truly complete class
See the code section above
Modifier: public private final abstract
public means the keyword with the maximum permission in the class permission, indicating that the class itself can be used in this package and this project
Private is private, which means that the keyword of the minimum permission in the permission indicates that the class itself can use other variables or methods that cannot be modified by the keyword
final is a constant. A constant cannot modify its assignment content and the special use of some methods
Abstract is an abstract class. The meaning of an abstract class is to let subclasses inherit and rewrite methods without other contents. If the abstract class is decorated with static and private or is not rewritten, it will become meaningless
For constants and abstract classes, please continue to read the article for details
this reference of object

this keyword is mostly used to specify initialization objects and method calls
Statically decorated methods cannot use the this keyword

5.2 method details

Method is the abstraction of object behavior and is used to realize operation. From the design point of view, method is similar to function. Class cannot exist independently and must belong to object or class

Method parameter transfer mechanism

The local variable only passes its copy to the method as a parameter, but it has no effect on itself, that is, the number of variables in the heap has doubled

Method of variable number of formal parameters

public class Demo{
    public static void test(int a,String...strget){
        for(var str:strget){
            System.out.println(str);
        }
    }

    public static void main(String[] args) {
        test(5,"Hello","Hello");

    }
}

There can be at most one variable number of formal parameters in a method, and the variable number of formal parameters can only be at the end of the formal parameter list

Method overload

public class Demo{
    public void test(){
        System.out.println("Parameterless test method");
        System.out.println("----------------------------");
    }
    public void test(int testInt){
        System.out.println("Of one parameter test method");
        System.out.println(testInt);
        System.out.println("----------------------------");
    }
    public void test(int testInt,String testString) {
        System.out.println("Of two parameters test method");
        System.out.println(testInt);
        System.out.println(testString);
    System.out.println("----------------------------");
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.test();
        demo.test(14);
        demo.test(14,"Fried meat with garlic moss");
    }
}

The same method name and different parameter lists are overloads. Different parameter list inputs obtain different results and execution contents. It is not recommended to use a variable number of formal parameters in the formal parameters of overloaded methods, because this will greatly reduce the readability of the program

5.3 member variables and local variables

A member variable is a variable defined in a class
Local variables are variables defined in methods or code blocks
Member variables are divided into instance variables and class variables
If the static keyword is added before the variable, it is a class variable and can be called without an object

public class Demo{
    String str = "Hello";
    static String staticStr = "Java";

    public static void main(String[] args) {
        Demo demo = new Demo();
        System.out.print(demo.str);
        System.out.println(staticStr);
        String mainStr = "I'm a local variable";
        System.out.println(mainStr);
    }
}

Local variables are destroyed as soon as they leave the scope

5.4 encapsulation

The encapsulation of the three object-oriented features of Java generally means that there are many details in the program that should not be seen and touched by users. It should only be used by users without allowing users to write and other operations. It also hides its own details and does not produce unnecessary errors

How to implement encapsulation

The data is encapsulated by the permission modifier private

public class Demo{
    private int key = 252;

    public void setKey(int key) {
        this.key = key;
    }

    public int getKey() {
        return key;
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        System.out.println("key Variable is:"+demo.getKey());
    }
}

Methods are used to return key variables, and variable permissions are effectively controlled through set methods (setting) and get methods (obtaining). Set and get methods are also standardized in Java

Overload of constructor

Constructor overloading is roughly the same as method overloading

public class Demo{
    String name;
    int age;
    String like;
    public Demo(){}
    public Demo(String name,int age){
            this.age=age;
            this.name=name;
    }
    public Demo(String name,int age,String like){
        this(name,age);
        this.like = like;
    }

    public static void main(String[] args) {
        Demo demo1 = new Demo();
        Demo demo2 = new Demo("Luo Tianyi",15);
        Demo demo3 = new Demo("Luo Tianyi",15,"SingMusic");
        System.out.print("demo1 The name of the object is"+demo1.name+" ");
        System.out.println("demo1 The age of the object is"+demo1.age);
        System.out.print("demo2 The name of the object is"+demo2.name+" ");
        System.out.println("demo2 The age of the object is"+demo2.age);
        System.out.print("demo3 The name of the object is"+demo3.name+" ");
        System.out.print("demo3 The age of the object is"+demo3.age+" ");
        System.out.println("demo3 The object's hobbies are"+demo3.like);
    }
}

this(name,age) here is special. It directly calls another overloaded constructor to complete initialization

5.6 inheritance of classes

Class inheritance facilitates the reuse of the contents of some methods or constructors in the class and increases the flexibility of operations such as class extension. There is only one direct parent class of Java, and there is no complex and difficult to understand mechanism such as multiple inheritance
Implement keyword exends
Writing method
public class Demo extends JFrame{}
Class etends parent class
An inheritor becomes a subclass. In fact, a subclass is a special parent class. Therefore, the scope of a parent class is always larger than that of a child class. Therefore, it can be considered that a parent class is a large class and a child class is a small class. It can be regarded as a branch. The parent class is at the top level and the child class is a branch. Although there is only one direct parent class, multiple parent classes can be inherited from each other, But not multiple direct parents

import javax.swing.*;

public class Demo extends JFrame {
    public Demo(String title){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBounds(500,500,500,500);
        setTitle(title);
    }

    public static void main(String[] args) {
        Demo demo = new Demo("Implement forms by inheriting form classes");
        demo.setVisible(true);
    }
}

It can be seen that the subclass directly obtains the methods of the parent class, which can be realized through direct call and input parameters. Inheritance greatly enhances the reusability of the code

Override of parent method

Sometimes, when a subclass inherits the methods of its parent class, some methods may not be appropriate and need to be overridden

class Cat {
    public void hunting(){
        System.out.println("I'm an adult cat. I can prey on mice and break the darkness with thunder");
    }
}
class BabyCat extends Cat{
    public void hunting(){
        System.out.println("I'm just a kitten. I can only watch my mother hunt mice to learn. Double guns will tell you the answer");
    }
}
public class Demo{
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.hunting();
        BabyCat babyCat = new BabyCat();
        babyCat.hunting();
    }
}

It can be seen here that the kitten is the child of the mother cat (inheriting the mother cat), but the kitten can't realize the mother cat's hunting method now, so it must be rewritten into a reasonable method for the kitten

super limit

super keyword is mostly used to call overridden parent variables or methods
Not much to say, look at the code

public class Demo{
    public static void main(String[] args) {
        Men men = new Men();
        men.info();
        MenTow menTow = new MenTow();
        menTow.info();
    }
}
class Men{
    int age = 2;
    String name = "Horse cow force";
    String like = "take the video";
    public void info(){
        System.out.println("My name is"+this.name+"this year"+this.age+"Years old"+"Hobbies are"+this.like);
        System.out.println("Do you know how awesome I am?"+"I dare eat*Eat three kilograms a day! The more you eat, the more you force");
    }
}
class MenTow extends Men{
    float age = 0.5f;
    String name = "Old eight";
    String like = "eat the AoLiGei";
    public void info(){
        System.out.println("My name is"+this.name+"this year"+this.age+"Years old"+"Hobbies are"+super.like);
        System.out.println("Although not at the same time, but in the same toilet, I challenged Ollie again,Ollie did it, brothers");
    }
}

You can see that the output of like in the method called by the ManTow object is not its own content, but the content of the parent class. This is the result of the super keyword. Call the overridden method or variable

5.7 polymorphism

The same parent class has different method or constructor contents

public class Demo{
    public static void main(String[] args) {
        Bird birdOne = new Seagull();
        Bird birdTow = new Ostrich();
        birdOne.fly();
        birdTow.fly();
    }
}
class Bird{//Bird parent
    public void fly(){//Flying method
        System.out.println("Flying in the sky");
    }
}
class Seagull extends Bird{//Seagulls

    @Override
    public void fly() {
        System.out.println("I can fly freely in the sky");
    }
}
class Ostrich extends Bird{//Ostriches
    @Override
    public void fly() {
        System.out.println("I can only run on land");
    }
}

The results of two object calling methods are different, which is the effect of polymorphism

5.9 initial code block

Here is the value, which defines a set of braces directly in the program
{};
Modifiers can be added, but only static can be added
If a static identifier is added, it belongs to the class. On the contrary, it will be the instance initialization block

public class Demo{
    static{
        System.out.println("Static code block");
    };
    public static void main(String[] args) {
		//Demo demo = new Demo();// If static is removed, the content instance initialization block will be output only when the class object is created
    }
}

The function of initialization is roughly the same as that of the constructor. Both are used for initialization. The initialization code block will be automatically transferred to the constructor at run time, and will be at the front of all the codes of the constructor according to the sequence

Tags: Java Back-end

Posted on Sun, 28 Nov 2021 11:22:31 -0500 by phaseonemedia