Experiment two Java object-oriented programming

Source: Internet
Author: User
Tags getcolor

Experimental content

1. Initial mastery of unit testing and TDD

2. Understanding and mastering the object-oriented three elements: encapsulation, inheritance, polymorphism

3. Initial mastery of UML modeling

4. Familiarity with S.O.L.I.D principles

5. Understanding Design Patterns

Experimental requirements

1. Students who do not have a Linux base are advised to start with the Linux basics (new version) Vim Editor course

2. Complete the experiment, write the experiment Report, the experiment report is published in the blog site blog, note that the experimental report is focused on the results of the operation, problems encountered (tool search, installation, use, program editing, commissioning, operation, etc.), solutions (empty methods such as "Check Network", "Ask classmates", "reading" 0 points) as well as analysis (what can be learned from it, what gains, lessons, etc.). The report can refer to the guidance of Fan Fei Dragon Teacher

Experimental process:

(a) Unit testing

(1) Three kinds of code

Programming is intellectual activity, not typing, what to do before programming, how to do to think clearly to write the program, write well. With a lot of students at present, a program to open the editor to write code, I hope that students develop a habit, when you want to solve problems with the procedure, you will write three kinds of code:

Pseudo code

Product Code

Test code

We use an example to illustrate how to write these three kinds of code.

Requirements: We want to solve a percentile grade in a Myutil class turn into "excellent, good, medium, pass, fail" five grade system performance function.

Pseudo code:

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:

The good Myutil.java are as follows:

public class myutil{

public static String Percentage2fivegrade (int grade) {

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";

Other, turn into "error"

Else

return "error";

}

}

Test code:

public class Myutiltest {

public static void Main (string[] args) {

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

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

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

Else

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

}

}

Experiment:

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

This first write test code, and then write the product Code development method called "Test-driven Development" (TDD).

The general steps for TDD are as follows:

    • Clear the current functionality to be completed and record it as a test list
    • Quick completion of writing test cases for this feature
    • Test code compilation does not pass (no product code)
    • Write the Product Code
    • Test Pass
    • Refactor the code and ensure the test passes (refactoring the next lab session)
    • Cycle through the development of all functions

Based on TDD, we do not have an over-design situation, and the requirements are expressed through test cases, and our product code is only allowed to pass the test. There is a unit test tool JUnit in Java to aid in TDD, and we use TDD to rewrite the example of the previous percentile to five-point system, and realize the benefits of developing with the test tool support. Open Eclipse, click File->new->java Project to create a new Tdddemo Java project, such as:

The test results showed a red bar, indicating that the test failed, the red bar summarized the test situation, ran a test, no errors, a test failed. The following reasons are also clear: the test code in line tenth passed in 55 o'clock, the expected result is "failed", the code returned "error", modifyMyUtil.Java

The test results showed a green bar, indicating that the test passed.

The coding rhythm of TDD is:

    • Add test code, JUnit appears red bar
    • Modify the Product Code
    • JUnit appears green bar, Task complete
(ii) Object-oriented three elements (1) abstract

Abstract the meaning of the word refers to people in the cognitive thinking activities in the object of the appearance of the factors of abandonment and the essence of the extraction of factors . Abstract is a kind of thinking tool that people often use when they know complex things and phenomena, abstract ability of abstract thinking is very important in program design,"refine, simplifying, youbiaojili and seeking the same in different ways" has a great extent to determine the programmer's programming ability.
Abstraction is a matter of extracting the essential features of things and not considering their details for the time being. For complex system problems, we can solve problems by means of hierarchical abstraction. At the highest level of abstraction, the solution of the problem is described in a generalized way, using the language of the problem environment. In the lower layers of abstraction, they are described in a procedural way. When describing a problem solution, use a problem-oriented and implementation-oriented terminology.
In program design, abstraction consists of two aspects, one is process abstraction and the other is data abstraction.
Let's give an example to illustrate this. For example, with the following Java code:

System.out.println(1);System.out.println(2);System.out.println(3);

Can print out "1,2,3,4", want to hit "the" How to do? Most of the students ' practice is to copy the above code, plus a line:

System.out.println(1);System.out.println(2);System.out.println(3);System.out.println(4);

This is the practice of "copy-paste" development without learning the process abstraction. Did you solve the problem? Solved, but there are problems, such as want to print out "1..100" what to do? Paste 100 lines? These two pieces of code have three lines of duplicate code, violating a common programming principle dry (Don ' t Repeat yourself), the solution is to process the abstraction, write a function printn:

public void printn(int n){for(int i=1; i<=n; i++)System.out.println(n);}

The above two pieces of code can be used;

printn(3);printn(4);

Instead, print out "1..100" is also very simple, just call PRINTN (100);

(2) encapsulation, inheritance and polymorphism

The three elements of object-oriented (object-oriented) include: encapsulation, inheritance, polymorphism. Object-oriented thinking involves all aspects of software development, such as object-oriented analysis (OOA), Object-oriented design (OOD), and object-oriented programming (OOP). OOA decomposes The system according to the abstract key problem domain and focuses on what. Ood is an object-oriented implementation of the symbolic design system, which constructs the system into a "real-world" object in a way that is very close to the problem domain terminology, and focuses on howto implement the functional specification through the model. OOP is coded in a programming language (such as Java) on a design basis. The main line that runs through OOA, Ood, and OOP is abstraction.
Ood Modeling uses the graphical Modeling language UML (Unified Modeling Language), UML is a generic modeling language, we experiment with Umbrello for modeling, and Windows recommends that you use STARUML.

The result of a process abstraction is a function, and the result of the data abstraction is an abstract data Type,adt, which can be used as an ADT with inherited and polymorphic mechanisms. Data Abstraction is the core and origin of OOP.

The first element of the OO three elements is encapsulation, which is the encapsulation of data and related behaviors to be wrapped together to implement information hidden. Java uses classes for encapsulation, such as a dog class:

Publicclass Dog {private String color; Public String getcolor () {return color;} public void setColor (String color) {this.color = color;} public String bark () {return public String tostring () {return Span class= "hljs-string" > "the Dog ' s color is" + this.getcolor () + this.bark () +  "!";}}  

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.
DogClasses use classes and access control (Private,public) to hide Properties color , open interfaces setColor() , getColor() bark() and toString . The Dog class is a module that we can use with the following code to test the code and run the results as follows:

We can use class diagrams in UML to describe classesDog

As we can see, in UML, the property of a class can display its name, type, initialization value, and properties 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

Note: UML class diagrams show static relationships between classes, class- AnimalTest dependent Dog classes and Classes Cat , and UML relies on lines with arrows.
The corresponding test code and run results are as follows:

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 Dog requirements of Cat repeating code in classes and Classes 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 .

In addition, in the Umbrello UML diagram can be translated into Java code, there is Java code can also generate UML diagram.

(iii) design pattern preliminary (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 principle of class design is a good guide:

    • SRP (Single Responsibility Principle, sole responsibility principle)
    • OCP (open-closed Principle, open-closed principle)
    • LSP (Liskov substitusion Principle,liskov substitution principle)
    • ISP (Interface segregation Principle, interface separation principle)
    • DIP (Dependency inversion Principle, dependency inversion principle)

OCPis one of the most important principles in Ood, OCP the content is:

    • Software entities (class, modules, function, etc) should open for extension,but closed for modification.
    • Software entities (classes, modules, functions, etc.) should be open to expansion and closed to modifications.

Problems encountered and their solutions

The problem: In the first two experiments, because the network is too much power, so choose to complete on their own computer, and.

Another big problem is that the test code in the process of writing because the program is not very familiar with the writing, and finally to follow the product code to write the test code, so the test code has a lot of problems, spend a lot of time to modify.

Experimental Harvest

Although the experiment took a lot of time, but I also gained a lot. First of all, through this experiment, I am more familiar with the use of virtual machines, but also more adapted to the experimental model. Unit testing also helped me to improve my ability to guide me through the process of dealing with problems that might arise, and taught me to take into account the possibilities of writing programs later to improve the security of the code.

Through this experiment, I have also come into contact with a lot of knowledge, such as TDD, although unfamiliar, it is difficult to deal with, but for me is still more eye-opener. I think that through every Java experiment, not only improve my learning ability, but also cultivate a sense of perseverance, although some difficulties, still try to do, may end up still no results, but will try.

Exercise 1 uses TDD to design a complex that implements a complex number class.

Code:

Package Shiyanlou;

Complex print, add, subtract

public class Complextest {
Main method
public static void Main (string[] a) {
Complex B = New Complex (2, 5);
Complex C = New Complex (3,-4);
System.out.println (b + "+" + c + "=" + B.add (c));
System.out.println (b + "-" + c + "=" + B.minus (c));
System.out.println (b + "*" + c + "=" + b.multiply (c));
System.out.println (b + "/" + c + "=" + B.divide (c));
}
}

Complex class
Class Complex {
Private double m;//Real part
Private double n;//imaginary part

Public Complex (double m, double N) {
THIS.M = m;
THIS.N = n;
}

Add
Public Complex Add (Complex c) {
return new Complex (M + c.m, n + C.N);
}

Minus
Public Complex minus (Complex c) {
return new Complex (M-C.M, N-C.N);
}

Multiply
Public Complex Multiply (Complex c) {return new Complex (M * c.m-n * C.N, M * C.N + n * c.m);
}

Divide
Public Complex Divide (Complex c) {
Double d = math.sqrt (C.M * c.m) + math.sqrt (C.N * C.N);
return new Complex ((M * c.m + N * C.N)/D, Math.Round ((M * c.n-n * c.m)/d));
}

Public String toString () {
String rtr_str = "";
if (n > 0)
Rtr_str = "(" + M + "+" + N + "I" + ")";
if (n = = 0)
Rtr_str = "(" + M + ")";
if (n < 0)
Rtr_str = "(" + M + n + "I" + ")";
return rtr_str;
}
}

Operation Result:

2. Report the time of your PSP (Personal software Process)

Steps

Take

Percentage

Demand analysis

0.5h

10%

Design

1h 20%

Code implementation

1.5h 30%

Test

1h 20%

Analysis Summary

1h 20%

3. Summarize the benefits of unit testing

(1) Make it easy to modify test code without worrying about the test code that will affect the design.

(2) It is easier to find the problem at an early stage, the problem is not easy to accumulate, can be solved immediately.

Experiment two Java object-oriented programming

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.