Java zero foundation entry series – classes and objects in Day11 Java

@H_ 403_ 1 @ today we are going to talk about two very important concepts in Java - classes and objects.

What is a class and what is an object? Class is a general description of a specific set. For example, people, this class, in terms of external characteristics, have names, ages, ability to speak, ability to eat, etc. These are the same characteristics as human beings. What about the object? We keep saying that we want object-oriented programming, but we haven't found an object for so long. This object is not that object. The object in Java is an instance of a specific class, just like you and I are an instance of the human class, that is, we are all a specific object of human beings, and we have our own names and ages.

So why use the concepts of classes and objects?

This is a good question. Classes are the product of the transformation from process oriented programming to object-oriented programming. In the previous program, taking C language as an example, the design program is a collection of algorithm + data structure. First design the algorithm, and then select the appropriate data structure to use the algorithm. Now object-oriented programming is just the opposite. First select the appropriate data structure, and then design the corresponding algorithm to solve the problem. In short, process oriented focuses on how to do things, and uses the perspective of God to deal with things, while object-oriented focuses on who should do things, and the protagonists are objects of various types. Process oriented is to solve problems from top to bottom, while object-oriented is from bottom to top

Let's take a vivid chestnut. Double eleven is coming. It's time to chop your hands. What about the specific steps?

The facing process is as follows: first set the budget budget, then select goods a, B, C and D, add them to the collection one by one, and wait for double eleven, payment and completion. Step by step in an orderly manner. The name and price information of each commodity are stored and processed with two string arrays.

Object oriented is like this: because of the commodity data to be processed, you can build a commodity class goods, which has attributes such as name, link and price. In addition, you also need to manage the commodity budget. Therefore, you can build a shopping cart class cart, carry out statistical management on the commodity budget, add commodities, delete commodities and other methods, Then set up a money class to manage the finance in a unified way. There are methods such as setting budget and payment. After these classes are built, all you need to do is create a new commodity object, add a commodity object to the shopping cart, and then wait for the double 11, payment and completion.

In the object-oriented idea, the subject is the object, which solves the problem through the interaction between objects. As above, it focuses on objects such as commodities, while the process oriented focuses on how to solve the problem, that is, how to buy appropriate commodities within the budget.

Of course, you might say that at this point of view, object-oriented seems more complex and troublesome. For simple problems, it is true, because the emergence of object-oriented itself is to solve those complex projects and provide better maintenance methods. Therefore, the more complex the problem is, the more it can reflect the advantages of object-oriented. That's the problem. In that case, why do I lift the chestnut above to hit my face??? Don't worry. When you finish the following content, you can look back at this problem and know what's going on.

Now let's take a look at what classes in Java are like. As a rule, let's take a small chestnut first:

class Goods{
  String title;
  double price;
}

The simplest class is defined here because it is only used as an example. In fact, it is not useful. It is just to illustrate the general definition of a class, that is, class + class name followed by curly braces, and write the properties and methods of the class in curly braces. The title and price here are defined in the class, also called class member variables. Generally, the data variables or objects we need to pay attention to are defined at the front of the class. This part is also called the instance domain of the class. Class is defined. How do we use it if we need to use it? At this time, you need to use the new keyword to create an instance of the class, that is, an object.

  = =1.1="123"
class Goods{
    String title;
    double price;
}

Here, classes are defined and used in the same file. In fact, in order to facilitate management, each class is usually placed in a separate file, and the file name is defined by the class name. For example, the goods class is placed in goods Java file, and test is placed in test In a java file, which file references a class defined in another file will report an error? The answer is No. the compiler will automatically help us find it. Just write the class name and file name according to the specification. Of course, if you use IDE, the package to which the class belongs will be declared at the beginning. The concept of package has been described before, so I won't introduce it too much here. The compiler will automatically find the corresponding class in the package. However, you need to add the public keyword before the definition of goods to indicate that it can be called by external classes. If you need to use classes in other packages, you need to use the import keyword to import classes, such as import Java util.*; The * here represents importing Java All classes under util can be used as normal classes after import.

The class defined now has only attributes and no methods. It looks like a class that binds two data into one class, just like struct in C language. Next, we will extend this class.

First of all, we need to initialize our product title and price. Here, we forcibly use the initialization block (funny) for introduction.

 Goods{
    String title; price;
    {
        title = "";
        price = 0.0;
    }
}

Initialization block, as the name suggests, is a code block specially used for initialization. It will run before the constructor during class initialization, because the initialization of some variables is not as simple as assignment and needs some operations. If it is placed in the constructor, it will appear bloated, especially when there are multiple constructors. So the initialization block here is a series of overqualified and underused. It can be written in the following form. Here is only the content forcibly added to introduce the initialization block.

 Goods{
    String title=”“;double price=0.0;
}

Next, add a constructor. What is a constructor? Is a special method to construct this class. Each class has at least one constructor. Isn't there no chestnuts on it? In fact, if there is no explicit method to add a constructor, the system will provide a default parameterless constructor, but the constructor does nothing, so it will have no sense of existence. Now we should give it a sacred mission and make it valuable.

 Goods{
    String title="";public Goods(String aTitle, aPrice){
        title = aTitle;
        price = aPrice;
    }
}

The constructor name is consistent with the class name, preceded by the public modifier, and the parameter list is in parentheses. Here, two parameters are used to specify the title and price information of the class respectively. In this way, the test class can be written like this before.

new Goods("123",1.1);
        System.out.println(goodsA.price);
    }
}

Is it easier to use this way? The general simple initialization code will also be put into the constructor. We can also define multiple constructors.

 aPrice;
    }public Goods( aPrice){
        price = aPrice;
        title = "Goods";}
}
public class Test{
    public static void main(String[] args) {
        Goods goodsA = new Goods("notebook",1.1);
        Goods goodsB = new Goods(2.2);
        System.out.println("goodsA title:"+goodsA.title+" price:"+goodsA.price);
        System.out.println("goodsB title:"+goodsB.title+" price:"+goodsB.price);
    }
}

In this way, you can use either a constructor with two parameters or a constructor with only one parameter, which will execute different constructor methods.

The constructor has, and then two methods are added to read the price and title, and set the price and title.

 Goods{
    private String title="";
    private ;     aPrice;
    }     aPrice;
        title = "Goods";
    }    public String getTitle(){return title; 
    }     getPrice(){ price;
    }     setTitle(String aTitle){
        title = aTitle;
    }    void setPrice( aPrice;
    }
}

In this way, our class is already very full, bah, full. Here, we add four methods, two for reading member variables and two for setting member variables. In addition, we set the two member variables to private, so that the two member variables can only be used in methods inside the class and are prohibited in other classes. You may ask, why is it so complicated? Is it bad to operate two data directly? This is the meaning of encapsulation. Completely encapsulate the data in the class and only open the interface for access and modification. In this way, the class is like a socket. The external code does not need to know what is in the socket, but only needs to know whether it is a three hole socket or a two hole socket and how to use it. The advantage of this is that it can be easily maintained, Because the data form is easy to change, but as long as the provided interface does not change, other codes do not need to change, reducing the dependence between codes, so as to achieve the effect of modularization.

Now the test class needs to be adjusted accordingly, because the members of the goods class have been declared private, so they can only be accessed through class methods. Generally, the method used to access class members is called accessor, and the method used to set class members is called changer.

new Goods("notebook",1)">);
        Goods goodsB = new Goods(2.2);
        System.out.println("goodsA title:"+goodsA.getTitle()+" price:"+goodsA.getPrice());
        System.out.println("goodsB title:"+goodsB.getTitle()+" price:"+goodsB.getPrice());
    }
}

Well, now our class has become a little powerful. What if we need to add commodity links now?

 Goods{private String title=""private private String link = ""; aPrice,String aLink){
        title = aPrice;
        link = aLink;
    } aPrice;
        link = "www.baidu.com";
    };
        link = "www.baidu.com" title;
    } price;
    } String getLink() { link;
    } aTitle;
    } aPrice;
    } setLink(String aLink){
        link = aLink;
    }
}

Add a member variable and the corresponding accessor and modifier. Of course, a constructor is added here. In this way, not only the previous code can still be used, but also new methods can be used to show a new height.

);
        Goods goodsC = new Goods("Java class",233,"www.cnblogs.com/mfrank/p/7747587.html");
        System.out.println("goodsA title:"+goodsA.getTitle()+" price:"+goodsA.getPrice()+" link:"+goodsA.getLink());
        System.out.println("goodsB title:"+goodsB.getTitle()+" price:"+goodsB.getPrice()+" link:"+goodsB.getLink());
        System.out.println("goodsC title:"+goodsC.getTitle()+" price:"+goodsC.getPrice()+" link:"+goodsC.getLink());
    }
}

In this way, all the information of the three objects can be output. Don't you think it's too troublesome to output. If you repeat it three times or more, you need to consider using a function instead. Well, let's add an output method to our goods class.

 print(){
        System.out.println("title:"+title+" price:"+price+" link:"+link);
    }
}
);
        goodsA.print();
        goodsB.print();
        goodsC.print();
    }
}

You see, after our class is defined, does the code in the main function become very simple. This is the advantage of encapsulation. After encapsulation, you only need to know how to use it, and you don't need to pay attention to how to implement it internally.

Well, that's all about classes and objects. To sum up, a class is a feature description of a specific set, and an object is a specific instance of a class. When using a class, you need to use the new keyword to new an object, and then you can use class methods to operate the object. Class can be regarded as the template of an object. Like a factory, it can generate clothes, but the style of each dress can be different.

So far, this explanation is over. Welcome to continue your attention.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>