Thinking logic of computer programs (14), thinking Logic

Source: Internet
Author: User
Tags date now

Thinking logic of computer programs (14), thinking Logic

It is said that Tao shengyi has a second, second, and third life. If binary representation and operation are regarded as one, the basic data type is regarded as two, and the basic data type is regarded as three, then, the combination of classes and the inheritance introduced in the next section make the three born things.

In the previous section, we introduced some basic concepts and syntaxes of the class through the class Point. The class Point only has the basic data type, but the member variable type in the class can also be another class, the combination of classes can express more complex concepts.

Programs are used to solve practical problems. ing concepts in reality into concepts in programs is a step-by-step in the programming process for beginners. This section uses some examples to demonstrate how to express and process some real concepts and problems through the combination of classes and classes.

First, we will introduce two basic classes: String and Date. They are all classes in Java API, representing the text String and Date respectively.

Basic Class

String

String is a class in Java API that represents multiple characters, namely, a piece of text or String. It is an array of char. It provides several methods for convenient String operations.

The String can be initialized with a String constant, and the String constant is enclosed in double quotation marks (note the difference with the character constant, and the character constant is enclosed in single quotation marks). For example, the following statement declares a String variable name, assigned as "programming by Ma"

String name = "programming ";

The String class provides many methods for operating strings. In Java, because String is widely used, Java has some special processing for it. This section does not introduce this content for the time being, but treats it as a String type.

Date

Date is also a class in Java API, which represents the Date and time. It is a long type value internally. It also provides several methods to operate on the Date and time.

Create a Date object using the construction method without parameters. This object indicates the current time.

Date now = new Date();

Date and time processing are a long topic. We will leave it for further details. In this section, we will only treat it as a type that represents the date and time.

Graphics

Extended Point

First, we need to extend the Point class, add a method in it, and calculate the distance to another Point. 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));}

Line

In type Point, attributes x and y are all basic types, but the attributes of a class can also be classes. We consider a class that represents a line, which consists of two points, there is an instance method to calculate the line length, the Code is as follows:

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 composed of two points. These two points are required when the Line is created. Therefore, there is only one constructor and the two points must be passed. The length method calculates the length of the Line, it calls the Point distance calculation method to obtain the line length. We can see that in the design line, the level we consider is the point, not the internal details of the point. Each class encapsulates its internal details and provides high-level external functions so that other classes can consider and solve problems at a higher level. This is a basic way of thinking in programming.

The code for using this class is as follows:

public static void main(String[] args) {    Point start = new Point(2,3);    Point end = new Point(3,4);        Line line = new Line(start, end);    System.out.println(line.length());}

This is also very simple. Let's talk about the memory layout. The two instance members of line are reference types and reference the actual point. The overall memory layout is roughly shown in:

The three reference variables start, end, and line are allocated to the stack and the actual content address is saved. The actual content is saved in the heap. The two instance variables of line are still referenced, the actual content address is also saved.

E-commerce concept

Next, we will use classes to describe some basic concepts in the E-commerce system. The most basic products, users, and orders in the E-commerce system:

  • Product: it has the unique Id, name, description, image, price, and other attributes of the product.
  • User: User Name, password, and other attributes.
  • Order: includes the order number, order user, list and quantity of purchased products, order time, consignee, shipping address, contact number, order status, and other attributes.

Of course, the actual situation may be very complicated, which is a very simplified description.

This is the Product code:

Public class Product {// unique id private String id; // Product name private String name; // Product image 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 attribute. Most of the sample code below will also be omitted.

This is the User-like code:

public class User {    private String name;    private String password;}

A single order may have multiple products, and each product may have a different quantity. We use the OrderItem class to describe a single product and the quantity to purchase. The Code is as follows:

Public class OrderItem {// Purchase 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 references the Product class. We define a constructor and a method for calculating the price of this order.

The following is the Order code:

Public class Order {// Order number private String id; // purchase User private user User; // purchase product list and quantity private OrderItem [] items; // Order time private Date createtime; // private String recipient; // recipient address private String address; // contact number private String phone; // order status private String status; public double computeTotalPrice () {double totalPrice = 0; if (items! = Null) {for (OrderItem item: items) {totalPrice + = item. computePrice () ;}} return totalPrice ;}}

The Order class references the User class and the orderItems array of an Order entry. It defines a method for calculating the total price. Here, a String class is used to indicate the status, which is more suitable for enumeration. We will introduce enumeration in subsequent articles.

The above class definition is very simplified, but it roughly demonstrates the process of ing realistic concepts into classes and combinations of classes. This process is probably to think about the concepts of the actual problems, the following describes the attributes, behaviors, and relationships between these concepts, and then defines the relationships among classes, attributes, methods, and classes. Concepts may have many attributes and behaviors, but the defined classes only need to include the actual problems.

Person-Person

The graphic class and E-Commerce class described above only reference other classes, but a class definition can also reference itself. For example, we want to describe the kinship between people, we use the class Person to represent a Person. Its instance members include the father, mother, and children. These members are also of the Person type.

The following code is used:

Public class 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, it seems that this is hard to understand and is somewhat similar to recursive calls in function calls. The key point here is that instance variables do not need to have values at the beginning. Let's take a look at how to use it.

Public static void main (String [] args) {Person laoma = new Person ("Old Horse"); Person xiaoma = new Person ("Pony"); xiaoma. setFather (laoma); laoma. setChildren (new Person [] {xiaoma}); System. out. println (xiaoma. getFather (). getName ());}

This code first creates laoma, then xiaoma, and then calls the setFather method of xiaoma and the setChildren method of laoma to set the parent-child relationship. The memory layout is roughly shown in:


Directories and files

Next, we will introduce two classes: MyFile and MyFolder, which respectively represent two concepts in file management, files and folders. Files and folders have names, creation times, and parent folders. The root folder does not have a parent folder. The folder also has a list of sub-files and subfolders.

The following is the code for file-like MyFile:

Public class MyFile {// file name private String name; // creation time private Date createtime; // file size private int size; // The parent directory private MyFolder parent; // other methods .... public int getSize () {return size ;}}

The following is the code of MyFolder:

Public class MyFolder {// folder name private String name; // creation time private Date createtime; // private MyFolder parent in the parent folder; // private MyFile [] files; // private MyFolder [] subFolders; public int totalSize () {int totalSize = 0; if (files! = Null) {for (MyFile file: files) {totalSize + = file. getSize () ;}} if (subFolders! = Null) {for (MyFolder folder: subFolders) {totalSize + = folder. totalSize () ;}} return totalSize ;}// other methods ...}

Both MyFile and MyFolder omit the constructor, settter, and getter methods, as well as the Code for maintaining the parent-child relationship. This mainly demonstrates the composite relationship between instance variables. The two classes can be referenced by each other, myFile references MyFolder, while MyFolder also references MyFile. This is correct because, as mentioned earlier, these attributes do not need to be set at the beginning or must be set. In addition, we demonstrate a recursive method totalSize () to return the size of all the files in the current folder. This is a good scenario for recursive functions.

Notes

The variables and methods defined in the class are closely related to the problems to be solved. This section does not particularly emphasize what the problem is. The defined attributes and methods are mainly used to demonstrate basic concepts, adjustments should be made based on specific problems in actual application.

The type of the instance variable in the class can be defined at present, and the two classes can be referenced to each other. These variables may seem hard to understand at first, but the real world is like this, when creating an object, these values do not need to be available either at the beginning or not, so there is no problem.

The composite relationship between classes is implemented in Java, but there are two obvious differences in the logical relationship. One is inclusion, and the other is simple reference. For example, in Order, the relationship between Order and User is simple reference. User exists independently, and the relationship between Order and OrderItem is include. OrderItem always belongs to an Order.
Summary

For beginners, it is unclear how to use program concepts to express real-world problems. This section uses simplified examples to explain how to map concepts in reality into classes in programs.

Break down the concepts involved in the actual problem and the relationships between concepts, express the concepts into multiple classes, and express more complex concepts and relationships between concepts through the combination of classes, it is a basic way of thinking for computer programs.

In addition to the combination, there is also a very important relationship between classes, that is, inheritance. Let's explore inheritance and its nature in the next section.

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

For more information, see the latest article. Please pay attention to the Public Account "lauma says programming" (scan the QR code below), from entry to advanced, ma and you explore the essence of Java programming and computer technology. Original article, retain all copyrights.

 

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.