preface

The previous has talked about some Java environment building, IDE use, variables and data types, operators, control flow and array operations, today to see a core idea in Java – object-oriented programming. The preview is as follows:

  • Introduction to Object Orientation
  • Object Oriented instance

object-oriented

What is object orientation?

Object oriented is a programming method that maps things in reality to computer models by means of objects.

The meaning of object refers to something concrete, that is, something we can see and touch in real life. In object-oriented programming, an object refers to a component in a computer system, which has two main meanings. One is data, and the other is action. That is, an object is a combination of the two, through which operations can be performed and the results of operations can be recorded.

Before that, another way of programming is procedural-oriented, which, as a concrete example, can be described as follows:

If one day you want to eat pickled cabbage fish, so what should you do? Here are two options for you, object-oriented and procedural, and let you decide which one to choose!

  1. Object oriented: Turn on your phone, open the delivery app, search for pickled cabbage and fish, and then place an order and wait for the delivery to arrive at home!
  2. Process oriented: first to buy vegetables, fish, sauerkraut, seasonings… Then go home to kill fish, cut pickled cabbage, cut spices… , and then start to fry, and finally put it on a plate!

The advantages and disadvantages of both can be found by comparison:

  • Process oriented
    • Advantages: Good performance; To take an example of their own than the starting point take-out, economic and affordable, but also eat assured;
    • Disadvantages: not easy to maintain, reuse, not easy to expand; For example, if we make our own food and want to eat something else, we have to go out and buy the ingredients. But takeout is not the same, directly open the phone and then point is!
  • object-oriented
    • Advantages: easy to maintain, easy to reuse, easy to expand, that is, process-oriented disadvantages;
    • Disadvantages: Poor performance; Ordering takeout is probably more expensive than making it yourself;

Three features of object orientation

  1. encapsulation

Hide object attributes and implementation details, external only provide access to the interface, improve reusability and security;

  1. inheritance

After the parent class is defined, the subclass can inherit from the base class, improving the code reuse rate. Important point: the class can only inherit;

  1. polymorphism

The reference variable of the parent class or interface definition can point to the instance object of the subclass or concrete implementation class, which improves the expansibility of the program.

Five principles of object orientation

  1. Single responsibility principle SRP

Class functionality should be single, not too complex;

  1. Open and closed principle OCP

A module is open for extension, but closed for modification, adding functionality, but not modifying functionality;

  1. The Richter substitution principle LSP

Subclasses can replace the parent class and appear anywhere the parent class can appear;

  1. Dependence inversion principle DIP

High-level modules should not depend on low-level modules, but should all depend on abstractions. Abstraction should not depend on concrete implementation, but concrete implementation should depend on abstraction;

  1. Interface separation principle ISP

It is better to design with multiple interfaces related to specific customer classes than with one generic interface;

A concrete example of object orientation

Classes and objects

Take our daily life for example, many of us now have pets, and pets all have some common states, such as name, color, age… So we can design something called a class that represents things like pets;

public class Pet{
    / / name
    public String name;
    
    / / the colour
    public String furColor;
    
    / / age
    public int age;
}
Copy the code

Once we have this class, it acts as a template from which we can create specific pets, which are called objects;

public class Pet{
    / / name
    public String name;
    
    / / the colour
    public String furColor;
    
    / / age
    public int age;
    
    public static void main(String[] args){
        // Create an object
        Pet dog = new Pet();
        dog.name = "Trying";
        dog.furColor = "white";
        dog.age = 1;
        
        Pet cat = new Pet();
        cat.name = "The short";
        cat.furColor = "orange";
        cat.age = 2; }}Copy the code

attribute

Each pet has its own set of states, such as name, coat color, and age, and these states are called attributes of a class. The type of an attribute can be either a primitive type (such as int in the above example) or a reference type (String in the above example). In the Java language, although the naming of attributes is not mandatory, there is generally a set of common naming methods, namely:

If the attribute is a single word, it is generally lowercase.

If the attribute is composed of multiple words, then the hump method is used.

For more naming rules, please refer to the Java Development Manual produced by Alibaba, download address: github.com/cunyu1943/a…

methods

Besides properties, each object can have many other functions, like pets can eat, bark… “, then these things that they can do can be represented by methods in a class;

public class Pet{
    / / name
    public String name;
    
    / / the colour
    public String furColor;
    
    / / age
    public int age;
    
    // The corresponding way to eat
    public void eat(a){
        System.out.println("Eat!);
    }
    
    // call the corresponding method
    public void bark(a){
        System.out.println("Bark!); }}Copy the code

For the method, there are several points to note:

  1. Methods can have a return value. If they return a value, the return type must be relative to the return value. For methods that do not need a return value, the return type is set tovoid;
  2. Methods can have parameters. In the above example, methods do not have parameters, but if we need, we can add our own parameters, but at this time pay attention to the type of parameters;

To sum up, it can be divided into the following four methods:

  1. No parameter no return value
public void methodName(a){
    ……
}
Copy the code
  1. No parameter has a return value
public boolean methodName(a){...return false;
}
Copy the code
  1. Parameter no return value
public void methodName(String name){
    ……
}
Copy the code
  1. There are parameters and return values
public boolean methodName(String name){...return false;
}
Copy the code
public class Pet{
    / / name
    public String name;
    
    / / the colour
    public String furColor;
    
    / / age
    public int age;
    
    // a method with a return value
    int getAge(a){
        return age;
    }

    // Method with arguments
    void setAge(int age){
        this.age = age;
    }
    
    // The corresponding way to eat
    void eat(a){
        System.out.println("Eat!);
    }
    
    // call the corresponding method
    void bark(a){
        System.out.println("Bark!); }}Copy the code

And for the method of naming, there is a certain attention to. Because methods are generally actions of a class, they usually start with a verb, and if there are multiple word combinations, use uppercase letters for the first letter of each word, except for all lowercase words.

A constructor

We talked about instances (that is, objects) and properties, so when we create an instance, we usually want to set its properties as well. In order to achieve this function, this is the time to add methods to achieve this goal, take the example of setting the age of the pet.

// Create an instance first
Pet pet = new Pet();
// Then call the method to set the age
pet.setAge(3);
// Check whether the age setting is successful
System.out.println(pet.getAge());
Copy the code

You can see that it is possible to do this by calling a method as described above, but suppose we need to set a number of properties and call setter methods many times to set all the property values. Once one is missed, the internal state of the instance will be out of order. Then we wondered, is there a simpler way to initialize the internal properties at the same time we create the instance object?

The answer: Yes! 🎉 🎉 🎉

In this case, we can use a special class of methods – constructors, and here’s what makes this constructor special.

The constructor is already called when we create the instance above, but it is a constructor with no arguments. Using the animal class Pet as an example, let’s see how to write its constructor.

public class Pet{
        / / name
    public String name;
    
    / / the colour
    public String furColor;
    
    / / age
    public int age;
    
    // no argument constructor
    public Pet(a){}
    
    // parameter constructor
    public Pet(String name, String furColor, int age){
        this.name = name;
        this.furColor = furColor;
        this.age = age; }}Copy the code

Above we only give the constructor with no arguments and the constructor with all attributes. In addition to the above two constructors, we can also create constructors with partial attributes as needed. As you can see, constructors have obvious characteristics compared to ordinary methods:

  1. No return value: Yes, constructors with and without arguments have no return value, and it is the default constructor for every class;
  2. Method names are the same as class names: the constructor name must be the same as the class name, otherwise it is not a constructor;

With the constructor, we can initialize the instance directly when we create it, instead of having to call the various setter methods to initialize the instance.

// Call the no-argument constructor
Pet pet1 = new Pet();
// Call the parameter constructor
Pet pet2 = new Pet("Corgi"."Yellow".1);
Copy the code

🎈 Tips: For instance attribute values, when not initialized by the constructor, there are default values for each data type: 0 for integer, 0.0 for floating point, false for Boolean, and NULL for reference type.

reference

Now that you know what object orientation is and some of the key concepts in object orientation such as objects, properties, and methods, it’s time to take a look at what a reference is.

The so-called reference, in fact, has been involved in the previous study. If you remember that String is a special data type, when we create a String, we create a reference.

String str = new String("Village Rain Yao");
Copy the code

STR is both a variable and a reference to a String with a value of “cun Yu Yao”. If we want to access the String, we need to use the STR reference to represent it.

We talked about one reference to one object, but we can also have multiple references to the same object. It’s like when you buy a car or two, not only you can drive it, but your wife can drive it, and your parents can drive it. The car is an object, and the person using it is a reference.

/ / object 1
String str1 = new String("Village Rain Yao");
2 / / object
String str2 = str1;
3 / / object
String str3 = str1;
Copy the code

conclusion

XDM, that’s it for today. It mainly talks about object-oriented concepts and characteristics, and introduces classes, objects, attributes, methods, constructors and references in object-oriented. About more object-oriented knowledge, we will see you in the next article!