Write in front: the blogger is a real combat development after training into the cause of the “hill pig”, nickname from the cartoon “Lion King” in “Peng Peng”, always optimistic, positive attitude towards things around. My technical path from Java full stack engineer all the way to big data development, data mining field, now there are small achievements, I would like to share with you what I have learned in the past, I hope to help you on the way of learning. At the same time, the blogger also wants to build a perfect technical library through this attempt. Any anomalies, errors and matters needing attention related to the technical points of the article will be listed at the end, and everyone is welcome to provide materials in various ways.

  • Please criticize any mistakes in the article and revise them in time.
  • If you have any questions you would like to discuss or learn, please contact me at [email protected].
  • The style of the published article varies from column to column, and all are self-contained. Please correct the deficiencies.

Basic units of action in Java – classes and objects

Keywords: class, property, behavior, instantiation, object \

The article directories

I. Brief analysis of concepts

Speaking of class and object, these are two abstract words, and if you use them in a program, you don’t know what they mean. In fact, we can first do not contact the procedure, we are in a lot of things when the classification of nature is a standard, meet some characteristics divided into one category, meet some other characteristics divided into another category. In each category, everything has the same characteristics, but there are some differences. Each thing is like an object, which is a real thing, while the classified category is like a standard or description, which is more abstract.

1. The concept of classes

In programming, we usually realize many application systems with the help of programs to meet the needs of daily life, such as online shopping, human resources management and so on. If you use object-oriented development, the first thing you need to do is to figure out what roles there are in the application system, what functions these roles can use, and what characteristics each role has.

We take a teaching management system as an example, the main function is to arrange courses, record the basic information of students and teachers, record and statistics of students’ academic performance. This mainly involves students, teachers and administrators. When a group of students enter the school, we need to input their information into the system, just like we have been filling in various forms. The information collected by each student is fixed, but the difference is the content of the information.



For example, we define a student class, and the student information we want to collect is the description of this class. The student has the student id, department and other basic information, which are also the inherent characteristics of students, so we can use the following code to describe:

// The class used to describe the student
public class Student{
    String sno;/ / student id
    String name;/ / name
    String college;/ / college
    String major;/ / professional. }Copy the code

2. What are objects

Once you understand the concept and representation of classes in your program, objects are easier to understand. To put it simply, an object is a specific thing that can be operated according to the standards of a class, that is, a specific student. Each student has the same characteristics, but can have different name, school, major, and so on their own information. To create a new object, use the following code:

public class Test{
    public static void main(String[] args){
        // Variable type Variable name = new class constructor ();
        Student student = new Student();
        // The uppercase Student is the type of Student we want to use, and the names must be exactly the same
        // Student in lowercase is the name of the object created by the student class
        // Is also the name we use directly when manipulating objects
        // New is the key used to create the object, and the corresponding constructor needs to be called
        // The use of constructors will be explained in a later article. For starters, remember: class name ();}}Copy the code

3. The relationship between classes and objects

As we have seen from the examples above, a class is like a template or a factory drawing, and objects are like individuals created according to this standard and mold, each of which has the same characteristics. Is reflected in the program, use the class keyword to define a class structure, and then in this structure to describe the entire class, what are the attributes that can be produced, but only a specific object can have specific attribute values and have the concrete behavior (about static statement will be separately in other articles).

Second, the class

How should we describe and define a class? Wasn’t the HelloWorld we originally wrote a class? Why aren’t there so many confusing concepts? Let’s go further.

From the perspective of the objective world, for example, Xiao Ming went to university, which is a specific student. He has his student number, name, corresponding school, major and so on, which are all his basic personal information. In addition, he can also carry out various activities, such as choosing courses, taking exams and modifying part of his information.



So how do we define a class from a program point of view? It depends on our needs, for a teaching management system, we only care about and students learning related information, students can choose courses, exams and so on. For a logistics management system, we are concerned about the students’ meal card consumption, access to the dormitory time, students can recharge, consumption, swipe cards and so on. So how to define and describe a class depends on the needs of our application system, or the requirements of the problem.

1. The attribute

Attribute refers to the current state of the class described, that is, some of its own information, directly defined under the class, and the normal declaration of a variable in the same format, can not specify the initial value.

2. Behavior

Behavior refers to the current class created by the object can carry out what kind of behavior, in the program performance is the method, can be called by the specific object, in the method body with code to achieve specific functions.

// The class used to describe the student
public class Student{
    // Student class attributes
    String sno;/ / student id
    String name;/ / name
    String college;/ / college
    String major;/ / professional.// Student behavior
    public void study(a){
        / / to learn
        System.out.println("Go to class");
    }
    public void exam(a){
        / / to the exam
        System.out.println("Go to the exam"); }}Copy the code

3. Executable classes

In general, we define a class that consists of four parts: properties, behaviors, constructors, and other methods that inherit Object. That is, there is no main method that we can execute directly, just to define a class that we want to use, so how do we call that and use our class? This is through classes that have main methods, such as HelloWorld, which we originally used, which is an executable class in its simplest form.

public class HelloWorld{
    public static void main(String[] args){
        System.out.println("Hello World!"); }}Copy the code

Of course, we can also directly add the main method to the class to test the run, but we usually do not do this, because there will be some permission issues can not test the complete, the usual method is to create a separate test class, to call the test.

// Call both classes in the same directory (in the same package)
public class Test{
    public static void main(String[] args){
        // Create a student object
        Student student = new Student();
        // Assign a value to an attribute of the object
        student.sno = "1130050152";
        student.name = "Xiao Ming";
        student.college = "School of Mathematical Sciences";
        student.major = "Information and Computing Science";
        // Displays the property values of the object
        System.out.println("The student's name is :" + student.name);
        // Call the method through the object, the behavior occursstudent.study(); student.exam(); }}Copy the code

Three, objects,

Above we have seen the concept of objects and how to create and use an object. Now let’s clarify the relationships between classes and objects, and between objects.

1. An object is an instance of a class

The process of creating an object can also be called instantiation, and objects can also be called instances of classes. This concept is also easy to understand. In a class, only a set of descriptions are defined. The actual implementation depends on concrete objects.

2. Relationships between objects

An important feature is that objects have something in common and do not interact with each other except for the use of statically declared properties. When we use different objects to call methods and output attribute information, although the structure of the class is completely the same, but because the state of the object (attribute value) may be different, so the result of method execution will be different.

// The class used to describe the student
public class Student{
    // Student class attributes
    String sno;/ / student id
    String name;/ / name
    double balance;/ / the balance.// Student behavior
    public void recharge(double money){
        // Recharge your student card
        balance += money;
        System.out.println("Current balance is" + balance);
    }
    public void getBalance(a){
        // Display the card balance
        System.out.println("Current balance is"+ balance); }}Copy the code
// Test classes: Put two classes in the same directory (in the same package)
public class Test{
    public static void main(String[] args){
        // Create the first student object
        Student student1 = new Student();
        // Assign a value to an attribute of the object
        student1.balance = 23.70;
        // Call the method
        student1.getBalance();
        student1.recharge(100.0);
        Create the second student object
        Student student2 = new Student();
        // Assign a value to an attribute of the object
        student2.balance = 15.60;
        // Call the method
        student2.getBalance();
        student2.recharge(50.0); }}Copy the code

After the execution of the program can be output again to view the property values of the two objects, will not affect each other.