Logic of the computer program (14)-The combination of classes "go"

Source: Internet
Author: User
Tags unique id

Just so-called, Daosh One, life two, two three, sansheng all things, if the binary representation and operation as one, the basic data type as two, the basic data type of the formation of the class as three, then the combination of classes and the following section introduces the inheritance is to make Sansheng everything.

In the previous section, we introduced the basic concepts and syntax of classes through class point, where there are only basic data types, but the types of member variables in a class can be other classes, and a more complex concept can be expressed through the combination of classes.

The program is used to solve the real problem, the concept of reality is mapped into the concept of the program, is a step forward in the process of learning programming. This section shows some examples of how to represent and process some of the real concepts and problems through a combination of classes and classes.

Let's start with two basic classes, string and date, all of which are classes in the Java API, representing text strings and dates, respectively.

Basic class


String is a class in the Java API that represents multiple characters, a piece of text or a string that is internally an array of char, which provides several methods for manipulating strings.

String literals can be initialized with a string constant enclosed in double quotation marks (note that the character constant is a single quote), for example, the following statement declares a string variable name and assigns a value of "old horse to say programming"

String name = "Old horse says programming";

The string class provides a number of methods for manipulating strings. In Java, because of the very common use of string, Java has some special handling of it, this section does not introduce this, just as a type of expression string to see.


Date is also a class in the Java API that represents a date and time, which is internally a long value, and it also provides several methods for manipulating the date and time.

Creates a new Date object with an argument-free construction method that represents the current time.

New Date ();

Date and time processing is a relatively long topic, and we leave it to the following chapters, this section we just look at it as a type of date and time.

Graphics class

Extend Point

Let's extend the point class to add a method to calculate the distance to the other, and the code is as follows:

Double distance (point p) {    return math.sqrt (Math.pow (X-p.getx (), 2)            +math.pow (Y-p.gety (), 2) );}


In type point, the attribute x, Y is the basic type, but the properties of the class can also be classes, we consider a class that represents a line, which consists of two points, and there is an instance method to calculate the length of the line, the code is as follows:

Class line {    private point start;    privatepublicthis.start=this.end =doublereturn start.distance (end);} }

Line is made up of two points, which are required to create line, so there is only one construction method, and it is necessary to pass the two dots, the length method calculates the lengths of the lines, and it calls the method of the point calculation distance to get the length of the lines. As you can see, when designing a line, we consider the level of point, regardless of the interior details of the point. Each class encapsulates its internal details, providing a high level of functionality to the outside world, allowing other classes to consider and solve problems at a higher level is a basic way of thinking about programming .

The code that uses this class is as follows:

void Main (string[] args) {new Point (    2,3 new Point (3,4New line (start, end); System.out.println (Line.length ());}    

This is also very simple. Let's explain the memory layout, the two instance members of line are reference types, referencing the actual point, and the overall memory layout is probably as follows:

Start, end, line three reference variables are allocated in the stack, save the actual content of the address, the actual content is stored in the heap, line of the two instance variable or reference, the same holds the actual content of the address.

E-commerce Concept

Next, we use the class to describe some of the basic concepts in the e-commerce system, the most basic of the e-commerce system has products, users and orders:

    • Product: Product unique ID, name, description, picture, price and other attributes.
    • User: A user name, password, and other attributes.
    • Order: Have the order number, the next single user, the purchase product list and quantity, the order time, the consignee, the receiving address, the contact telephone, the order status and so on property.

Of course, the actual situation can be very complex, which is a very simplified description.

This is the code for the Product class products:

PublicClass Product {// unique ID private String ID; // product name private String name; // product picture link private String Pictureurl; // Product description private String description; // product price private double price;         

We omit the constructor of the class and the Getter/setter method of the property, and most of the sample code below will be omitted.

This is the user-class code:

Class User {    private String name;    private String password;}    

An order may have multiple products, each product may have a different quantity, we use the order entry OrderItem this class to describe a single product and the number of options, the code is as follows:

PublicClassOrderItem {// buy product private product product; // purchase quantity private int quantity; public orderitem (product product, int quantity) {this.product = product; this.quantity = quantity;} public double Computeprice () {return product.getprice () *quantity;}}   

OrderItem refers to product class products, and we define a construction method and a method for calculating the price of the order entry.

The following is the code for order class orders:

PublicClassOrder {//Order numberPrivateString ID;//Buy a userPrivateUser user;//Purchase Product list and quantityPrivateorderitem[] items;//Time of orderPrivateDate Createtime;//ConsigneePrivateString receiver;//Shipping AddressPrivateString address;// contact phone private String phone; // order status private String status; public double Computetotalprice () {double totalprice = 0if (Items!=nullfor (OrderItem item:items) {Totalprice+=item.computeprice (); }} return Totalprice;}}      

The Order class references the user class, and an array of order entries, OrderItems, which defines a method for calculating the total price. Here, a string class is used to represent the state status, which is more appropriate for the enumeration type, and an enumeration of our subsequent articles.

The above class definitions are very simplified, but presumably demonstrate the process of mapping realistic concepts into classes and class combinations, presumably by thinking about the concepts of real-world problems, what properties they have, what behaviors, what the concepts are, and then defining classes, defining properties, defining methods, Defines the relationship between classes, presumably. The properties and behavior of the concepts can be very numerous, but the defined classes only need to include what is relevant to the real-world problem.


The graphic and e-commerce classes described above only refer to other classes, but a class definition can also refer to itself , for example, we want to describe the blood relationship between people and people, we use the class person to represent a human, its instance members include its father, mother, and children, These members are also the person type.

Here's the code:

Publicclass person {// name private String name; // father private  person father; // mother private person mother; // child array private person[] children; public person (String name) { this.name = name;}       

The Setter/getter method is also omitted here. For beginners, at first glance, this is more difficult to understand, a bit like recursive invocation in a function call, the key point is that the instance variable does not need to have a value at the beginning. let's see how it's used.

void Main (string[] args) {    new person ("Old horse"new Person ("Pony"); Xiaoma.setfather (Laoma); Laoma.setchildren (new person[]{xiaoma}); System.out.println (Xiaoma.getfather (). GetName ());}     

This code first creates the old horse (Laoma), then creates the Pony (Xiaoma), and then calls Xiaoma's Setfather method and Laoma's Setchildren method to set the parent-child relationship. The layout in memory is probably as follows:

Directories and files

Next, we introduce the two classes MyFile and MyFolder, which represent two concepts, files, and folders in file management, respectively. Files and folders have names, creation times, parent folders, no parent folders for the root folder, and a list of child files and subfolders for folders.

The following is the code for the file class MyFile:

PublicClassMyFile {// file name private String name; Span style= "COLOR: #008000" >// creation time private Date Createtime; // file size private int size; // parent directory private MyFolder parent; // other methods .... public int GetSize () { Span style= "COLOR: #0000ff" >return size;}}        

Here is the code for MyFolder:

PublicClassMyFolder {//Folder namePrivateString name;//Creation timePrivateDate Createtime;//Parent folderPrivateMyFolder parent;//Included filesPrivatemyfile[] files;//Contained subfoldersPrivateMyfolder[] subfolders;public int TotalSize () { Span style= "COLOR: #0000ff" >int totalsize = 0; if (Files!=nullfor (MyFile file:files) {totalsize+= file.getsize ();} } if (Subfolders!=nullfor (MyFolder folder:subfolders) {Totalsize+=folder.totalsize (); }} return totalsize;} // other methods ...}        

MyFile and MyFolder, we have omitted the construction method, Settter/getter method, and about the maintenance of the parent-child Relationship code, the main demonstration of the relationship between the instance variables, two classes can be referenced to each other,myfile reference MyFolder , and MyFolder also quoted MyFile, which is not a problem, because as previously mentioned, these properties do not need to be set at the beginning, nor must be set. In addition, a recursive method TotalSize () is shown to return the size of all files under the current folder, which is a good scenario for using recursive functions.

Some notes

What variables are defined in the class, and which are closely related to the problem to be solved, this section does not specifically emphasize what the problem is, the properties and methods defined are primarily used to demonstrate the basic concepts, and the actual application should be adapted to specific problems.

The type of an instance variable in a class can be a currently defined type, and two classes can be referenced to each other, which may sound difficult to understand, but in the real world, these values do not need to be there at first, or not, to create objects, so there is no problem.

The combined relationship between classes, implemented in Java is a reference, but on a logical relationship, there are two distinct relationships, one is included, the other is simple reference . For example, in order class orders, the relationship between order and user is a simple reference, the user is independent, and the relationship between order and OrderItem is contained, OrderItem always belongs to an order.

For novice programmers, it is unclear how to use procedural concepts to express real-world problems, and this section explains how to map real-world concepts into classes in programs by simplifying examples.

It is a basic way of thinking of computer programs to decompose the concepts involved in real problems and the relationships between them, to express concepts as multiple classes, and to express more complex concepts and relationships among concepts through the combination of classes.

The relationship between classes, in addition to the combination, there is a very important relationship, that is, inheritance, let us explore the next section of inheritance and its essence.


Logic of the computer program (14)-The combination of classes "go"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.