Logic of the computer program (14)-a combination of classes

Source: Internet
Author: User

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

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

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:

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

Lines-Line

In type point, property x, Y are basic types, but the properties of a class can also be classes, we consider a class that represents a line, which consists of two points, and an instance method that calculates the length of the line, with the following code:

 public  class   line { private   point start;         private   point end;  public   line (point start, point end) {this . Start= start;     this . End = end;  public  double   Length () { return   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:

 Public Static void Main (string[] args) {    new point (2,3);     New Point (3,4);         New 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:

 Public classProduct {//Unique ID    PrivateString ID; //Product Name    PrivateString name; //Product Image Link    PrivateString Pictureurl; //Product Description    PrivateString description; //Product Price    Private DoublePrice ;}

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:

 Public 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:

 Public classOrderItem {//Buy Products    Privateproduct product; //Purchase Quantity    Private intquantity;  PublicOrderItem (product product,intquantity) {         This. Product =product;  This. Quantity =quantity; }     Public DoubleComputeprice () {returnProduct.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:

 Public classOrder {//Order Number    PrivateString ID; //buy a user    Privateuser User; //Purchase Product list and quantity    Privateorderitem[] items; //Time of order    PrivateDate Createtime; //Consignee    PrivateString Receiver; //Shipping Address    PrivateString address; //Contact Phone    PrivateString Phone; //Order Status    PrivateString status;  Public DoubleComputetotalprice () {DoubleTotalprice = 0; if(items!=NULL){             for(OrderItem item:items) {totalprice+=Item.computeprice (); }        }        returnTotalprice; }}

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.

People-person

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:

 Public classPerson {//name    PrivateString name; //Father    PrivatePerson father; //Mother    PrivatePerson mother; //Child Array    Privateperson[] Children;  PublicPerson (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.

 Public Static 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:

 Public classMyFile {//file name    PrivateString name; //creation Time    PrivateDate Createtime; //File Size    Private intsize; //Parent Directory    PrivateMyFolder Parent; //other methods ....         Public intGetSize () {returnsize; }}

Here is the code for MyFolder:

 Public classMyFolder {//folder name    PrivateString name; //creation Time    PrivateDate Createtime; //parent Folder    PrivateMyFolder Parent; //Included Files    Privatemyfile[] files; //contained subfolders    Privatemyfolder[] subfolders;  Public inttotalsize () {intTotalSize = 0; if(files!=NULL){             for(MyFile file:files) {totalsize+=file.getsize (); }        }        if(subfolders!=NULL){             for(MyFolder folder:subfolders) {totalsize+=folder.totalsize (); }        }        returntotalsize; }    //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.
Summary

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.

----------------

To be continued, check out the latest articles, please pay attention to the public number "old Horse Programming" (Scan the QR code below), from the introduction to advanced, in layman's words, Lao Ma and you explore the nature of Java programming and computer technology. Original article, All rights reserved.

Logic of the computer program (14)-a combination of classes

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.