Experiment two Java object-oriented programming

Source: Internet
Author: User
Tags visibility

20135101 Cao Yujing Experimental content 1. Preliminary knowledge of unit testing and TDD2. Understand and master the object-oriented three elements: encapsulation, inheritance, polymorphism 3. Initial mastery of UML modeling 4. Familiar with the S.O.L.I.D principle 5. Understanding the design pattern of the experiment requirements 1. Students without Linux Foundation are advised to first learn the basic Linux Basics (new version), VIM Editor Course 2. Complete the experiment, write the experiment Report, the experiment report is published in the blog Garden in the blog, notice the experiment report focus is Run Results, encountered the problem(Tools find, install, use, program edit, Debug, run, etc.), Solutions(empty methods such as "Check Network", "Ask classmates", "reading" and so on are 0 points) and Analysis(What can be learned from it, what gains, lessons, etc.). The report can refer to the guidance of Fan Fei Dragon Teacher 3. Plagiarism is strictly forbidden, and the results of the experiment of the perpetrator are zero, and other punitive measures are added. 4. please first in the laboratory building in the ~/Code directory with their own school number to create a directory, code and UML diagram to put in this directory, no study number will require redo, and then follow the following steps to practice。 Experimental steps: (i) unit Test (1) Three kinds of code

(1) Three kinds of code

Pseudo code

Product Code

Test code

Cases:

Requirement: Solve a percentile in a myutil class turn into "excellent, good, medium, pass, fail"

The function of grade five grades.

Write the Pseudo-code first:

/*

Percentile five-point system:

If the score is less than 60, turn into "fail";

If the score is between 60 and 70, turn into "pass"

If the score is between 70 and 80, turn into "medium"

If the score is between 80 and 90, turn into "good"

If the score is between 90 and 100, turn into "good"

Other, turn into "error"

*/

Product Code:

public class Myutil {

public static String Percentage2fivegrade (int grade) {

If the score is less than 0, turn to "error"

if (Grade < 0)

return "error";

If the score is less than 60, turn into "fail"

If (Grade < 60)

Return "Failed";

If the score is between 60 and 70, turn into "pass"

else if (Grade < 70)

return "Pass";

If the score is between 70 and 80, turn into "medium"

else if (Grade < 80)

Return "Medium";

If the score is between 80 and 90, turn into "good"

else if (Grade < 90)

return "good";

If the score is between 90 and 100, turn into "good"

else if (grade <= 100)

return "excellent";

If the score is greater than 100, turn to "error"

Else

return "error";

Other, turn into "error";

}

}

Test code: (Test module for Myutil.java)

public class Myutiltest {

public static void Main (string[] args) {

Percentile score is 50 o'clock should return to five grade system "failed"

if (Myutil.percentage2fivegrade (50)! = "Failed")

System.out.println ("Test failed!");

Else

System.out.println ("Test passed!");

}

}

Test Cases (TestCase) are a set of test inputs, execution conditions, and expected results for a particular goal to test a program path or verify that a specific requirement is met.

(2) TDD (test driven development, testing-driven development)

Write the test code first, then write the product code

General steps:

Clear the current function to complete, record a test list;

Quickly finish writing test cases for this function;

Test code compilation does not pass (no product code);

Write product code;

Test pass;

Refactor the code and ensure that the test passes (refactoring the next experiment);

Cycle to complete the development of all functions;

Goal of TDD: clean Code that Works.

The slogan of TDD is: Keep the bar green,to Keep the code clean.

The coding rhythm of TDD is:

Add test code, JUnit appears red bar;

Modify the product code;

JUnit appears green bar, task completed;

Open Eclipse, click File->new->javajava Project to create a new Tdddemo item

In the Tdddemo project, right-click Tdddemo,new->source Folder to create a new test catalog.

Right-click Test, New->junit test case, create a new test cases class Myutiltest

Add the first test case testnormal, note that there must be an annotation @test before the test case.

The test result is red bar, the test is wrong;

The test result is green bar, test pass.

(ii) Object-oriented three elements

(1) Abstract

Refine, Youbiaojili, simple, different

Complex system problems--hierarchical abstraction

The highest level of abstraction, using the language of the problem environment to describe the solution of the problem in a generalized way;

The lower layers of abstraction are described in a process-based manner;

Abstraction consists of two aspects: Process abstraction Data abstraction

(2) encapsulation, inheritance and polymorphism

Object-oriented (object-oriented) Three elements: encapsulation, inheritance, polymorphism.

Object-oriented Analysis (OOA) decomposes the system according to the abstract key problem domain;

Object-oriented design (OOD) provides the object-oriented implementation of the symbolic design system and implements the function specification through the model.

The object-oriented programming implementation (OOP) is encoded in the programming language based on the design.

Ood Modeling uses the graphical Modeling language UML (Unified Modeling Language), STARUML is recommended in Windows.

The result of the process abstraction is the abstract data type (Abstractdata Type,adt) of the result of the function, the data abstraction, and the class can be used as an ADT with inheritance and polymorphism mechanisms. Data abstraction is the core and origin of OOP.

Encapsulation-wraps data with related behaviors for information hiding. Classes are encapsulated in Java.

Encapsulation actually uses methods to hide the data of the class, controlling the user's modification of the class and the degree of access to the data, resulting in the benefits of modularity (modularity) and information hiding (information hiding);

Interface (interface) is an accurate description of the package.

Open the shell in the lab building environment, enter it on the command line umbrello , open the UML modeling softwareumbrello

Click the class icon on the toolbar, click in the box, and class diagram(类图) a Christmas box will pop up, enter the class nameDog。

把鼠标放到Dog类上,单击右键,选择Properties,在弹出的对话框中的Display中去掉Public Only选项,把鼠标放到Dog类上,单击右键,选择New->Attribute,在弹出的对话框中的填好Type,Name,并选好Visibility。把鼠标放到Dog类上,单击右键,选择New->Operation,在弹出的对话框中的填好Type,Name,并选好Visibility。

In UML, the property of a class can display its name, type, initialization value, and attributes can also display private,public,protected. The methods of the class can display their method names, parameters, return types, and the Private,public,protected property of the method. which

    • + indicates public
    • #表示 protected
    • -Indicates private

Please note that the representation of inheritance in UML class diagrams is to use a triangular line to refer to the parent class, through inheritance, we eliminate the duplicate code in the dog class and cat class, conforming to the requirements of dry. Inheritance refers to the definition of a class that can be based on another already existing class, that is, the subclass is based on the parent class, thus implementing the reuse of the parent code. The existing classes are called base classes, superclass, parent classes (base class, Super class, parent Class), and the new classes are called derived classes, inheriting classes, subclasses (derived class, inherited class, child class). An inheritance relationship expresses the relationship of "is a kind of", called the "ISA" relationship. The key to inheritance is to confirm that a subclass is a special type of parent class. Inheritance is the foundation of software reusability, and it is the main way to improve the expansibility and maintainability of software system. As shown above, based on encapsulation, inheritance can implement code reuse, it should be noted that inheritance more important role is to implement polymorphism. Object-oriented objects allow different classes of objects to respond to the same message, which means that the same message can be used in a variety of different ways depending on the sending object, and we call this behavior polymorphic. In Java, polymorphism refers to a phenomenon in which different class objects execute different code when they invoke the same signed member method. Polymorphism is the basis of the flexibility and extensibility of object-oriented programming.

Test code:

(iii) Preliminary design pattern

(1) S.O.L.I.D principle

Object-oriented three elements are "encapsulation, inheritance, polymorphism", and any object-oriented programming language will support these three elements syntactically. It is very difficult to use the three elements, especially polymorphism, with the help of abstract thinking, and the S.O.L.I.D design principle is a good guide:

The behavior of the extended open for Extension software module must be extensible, when the application needs change or needs to meet the new application needs, we have to let the module work in different ways, the modification is closed (Closed for modification Requires that the source code of the module is not modifiable, and no one is allowed to modify the existing module. Based on the OCP, with the object-oriented polymorphism (polymorphic), more flexibility in handling change embrace changes, the OCP can be implemented by: (1) abstraction and inheritance, (2) interface-oriented programming. For example, in a graphics system, there are already three module shape,square,circle, as shown in:

User now large need a triangle module is a reasonable request, because we use Polymorphic, the original module does not need to change, as long as the new add a module triangle can be.

The SRP content is: there should never is more than one reason for a class to change.

objects provide a high degree of encapsulation of a single responsibility, and object changes depend only on the change of a single responsibility, which is based on the definition of high cohesion in software design.

Content of LSP:

The core idea of LSP is that a parent type object can be overridden by a quilt type object.

The LSP principle clearly states that the "Isa relationship" in Ood is in terms of behavioral functions. The Behavioral function (behavior) is not intrinsic, private, but external, public, and is the interface that the client program relies on.

Content of the ISP: clients should not being forced to depend upin interfaces, that they does not use.

First of all to understand the customer is what, before a XXXX class, to have a matching xxxxtest class, xxxxtest to use the XXXX class, Xxxxtest class can be regarded as the XXXX class of customers.

There are too many functions of interface Rowsetmanager, we should divide this interface into multiple interfaces to facilitate reuse.

Dip content:

Through the interface or abstract class, dip in the application through the method of dependency injection decoupling, reuse of low-level modules, reuse implementation, release dependency. Let's look at an example: Imagine a simple program whose task is to make a copy of the keyboard input to the printer. It is further assumed that the implementation of the operating system in the platform does not support device independence.

The upper function copy relies on the lower function read,write. The dip changes the direction of the dependency, requires the following dependencies above, we use the abstract class to implement the dip.

(2) mode and design mode

A pattern is a customary solution (solution) for a particular problem (problem) under an external environment (context). The pattern must make the problem clear, explain why it is used to solve the problem, and under what circumstances it will not work, and each pattern can be reused because of its repeatability, having its own name, being able to impart it, and transplanting it into different scenarios. Patterns can be seen as expert solutions to a problem that can be reused.

The most important thing here is the design pattern, the position of design pattern in object-oriented can be equal to the position of data structure in process programming.

(3) design pattern Real Example

Design pattern provides a subsystem or component for refining a software system, or a diagram between them, which describes the public rendition structure of a communication component, which can solve a design problem in a particular context.

As the number of objects in the system increases and the interactions between objects grow exponentially, design patterns can help us design the system in the best possible way. Behind the design pattern is the principle of abstraction and solid. There are four basic elements of the design pattern:

There are many other object-oriented principles beyond the solid principle.

(iv) Exercise 1 using TDD to design a complex that implements a complex number class. 2. Report the time of your PSP (Personal software Process)

Steps

Take

Percentage

Demand analysis

10min

13.3%

Design

15min

20%

Code implementation

20min

26.7%

Test

20min

26.7%

Analysis Summary

10min

13.3%

Pseudo code:

1) Properties of the plural class ComplexNumber
Realpart: Real part, representing the real portion of a complex number
Imaginpart: Imaginary part, representing the imaginary part of a complex number
2) method of complexnumber of plural class
ComplexNumber () constructor, set the real part, the imaginary part to 0
ComplexNumber (double Realpart, double Imaginpart) constructor to create complex objects while completing real parts of complex numbers, initialization of imaginary parts
Getrealpart () get the real part
Getimaginarypart () Get imaginary part
Getrealpart (double realpart) set the real part
Getimaginarypart (double imaginpart) Set imaginary part
Add (ComplexNumber c) Complex sum
Add (double realPart2) complex sum
Minus (ComplexNumber c) Complex subtraction
Minus (double realPart2) plural subtraction
Complexmulti (ComplexNumber c) Multiply plural
Complexmulti (double realPart2) Multiply plural
ToString () combines the real part of the current complex object with the imaginary part into a a+bi string form

The Product code is:

Test code:

"Experimental Experience"

Through the TDD mode programming, the product code can be tested and perfected by the result, which can make the product code more rigorous and perfect.

In this experiment, I not only learned a lot of the principles of the development process, but also realized that their lack of learning, I need to learn more in the future of life in practice. Also learned some new knowledge, if you find bugs or new features added, you can immediately run unit tests to verify that the previous completed code is correct.

Experiment two Java object-oriented programming

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.