Experiment two Java object-oriented programming

Source: Internet
Author: User

Beijing Institute of Electronic Technology (BESTI)

Real Inspection report

Course: Java Programming Class: 1352 Name: Wang Gui No.: 20135207

Score: Instructor: Lou Jia Peng Experimental Date: 2015.5.8

Experimental classification: No preview degree: Experimental time: 15:30~18:00

Instrument Group: 07 Compulsory/Elective: Elective experiment number: 02

Experiment Name: Java Object-oriented programming

Experimental purposes and requirements:1.Initial mastery of unit testing andTDD;2.understand and master the object-oriented three elements: encapsulation, inheritance, polymorphism;3.Preliminary MasteryUMLmodeling;4.familiar withS.O.L.I.Dprinciples;5.Learn about design patterns.                                                                    

Experimental instrument:

Name

Model

Number

PC Machine

Lenovo Z485

1

Linux virtual machines

Ubuntu (32bit)

1

Experimental steps

One, Unit test

    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. When we want to use the program to solve the problem, we will write three kinds of code:

    • Pseudo code
    • Product Code
    • Test 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:

Product Code:

Test code:

After several modifications, you get the code that you can test yourself, that is, the code that implements the requirement.

At this point the test is expected, and when we make the Myutil.java available to others, others can meet the requirements as required. In order to ensure the unit measure is sufficient, our general requirement is that the test code is more than the product code.

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

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.

Here's how:

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

Select New->source folder in the popup menu to create a new test catalog.

We put the mouse on the test directory, right-click, select the New->junit test case in the popup menu to create a new test cases class Myutiltest

We add the first test case testnormal, note that before the test case must have the annotation @test, the test case method name arbitrary

There is a syntax error in the Red Fork in the figure, the reason is simple, the Myutil class does not exist, the Percentage2fivegrade method in the class does not exist, we create a myutil class in the SRC directory of Tdddemo, and implement the Percentage2fivegrade method, as shown in:

The test results showed a red bar, indicating that the test failed,

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

Two, object-oriented three elements

1. Abstraction

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 how to 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:

Encapsulation actually uses methods to hide the data of the class, controlling the user's modifications to the class and the extent to which the data is accessed, resulting in the benefits of modularity (modularity) and information hiding (information hiding) Interface (interface) is an accurate description of the package. The dog class hides the attribute color by using class and access control (private,public), opening the interface 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 the class diagram in UML to describe the class dog, first we open the shell in the lab building environment, enter Umbrello on the command line, open the UML modeling software Umbrello, as shown in:

Click on the class icon on the toolbar, then click in class Diagram, pop up a Christmas box, enter the class name dog, we put the mouse on the dog class, right-click, select Properties, in the popup dialog box in the display to remove the public Only option, we put the mouse on the dog class, right-click, select New->attribute, in the popup dialog box fill in the Type,name, and choose good visibility, we put the mouse on the dog class, right-click, select New-> Operation, fill in the popup dialog box Type,name, and choose good visibility, we can see, in UML, a class of properties can display its name, type, initialization value, 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

Using UML lets us not focus on the details. Similarly, we can build a cat class at this point in the test class as shown in the following UML diagram:

Note: UML class diagrams show static relationships between classes, animaltest classes rely on the dog class and cat classes, and UML relies on lines with arrows. The corresponding test code and run results are as follows:

We see that both the dog and cat classes have the color attribute and the corresponding setter and getter methods, which clearly violate the dry principle mentioned earlier, and we can solve this problem through inheritance. Place the Color property and the corresponding setter and getter methods in the parent class animal, as shown in the following UML:

The representation of inheritance in UML class diagrams is to use a triangular line to point 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. Looking at the previous class diagram, we can further abstract the bark () and meow () in the Cat class into an abstract method shout (), which overrides this method in the dog class and Cat class, as shown in the following UML diagram:

The shout () method in the animal class in the UML class diagram is an abstract method, italic, animal class is abstract and italic. The corresponding code and operation results are as follows:

In Java, when we use the parent class to declare a reference, when we use the subclass to generate the object, polymorphism appears

Three, the 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 design principle 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)

1). OCP is one of the most important principles in Ood, and the OCP's 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.

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.

Users now need a triangle module is a reasonable requirement, because we use Polymorphic, the original module does not need to change, as long as the new add a module triangle can be, as shown:

This graphics system is compliant with the OCP principle.

2). The SRP content is:

    • There should never be + than one reason for a class to change
    • Never have more than one reason to modify a class

3). The LSP content is:

    • Subtypes must is substitutable for their base types
    • Functions that use pointers or references to base classes must is able to use objects of derived classes without knowing I T
    • The subclass must be able to be used by its base class
    • Using a pointer to a base class or a referenced function, you must be able to use it without knowing the specific derived class object type (LSP is presented by Ms. Liskov)

4). The core idea of LSP is that a parent type object can be overridden by a quilt type object. The example of the animal,dog,cat that we have previously cited is in line with the LSP principle.

5). The content of the ISP is:

    • Clients should not being forced to depend upon interfaces the They do
    • Customers should not rely on interfaces that they do not use

6). The content of the dip is:

    • The modules should not depend upon low level modules. Both should depend upon abstractions
    • Abstractions should not depend upon details. Details should depend upon abstractions
    • High-level modules should not be dependent on low-layer modules. Both should be dependent on the abstract
    • Abstraction should not depend on detail. Details should depend on abstraction

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. There are many patterns in computer science:

    • Grasp mode
    • Analysis mode
    • Software Architecture Patterns
    • Design Patterns: Created, structured, behavioral
    • Management mode: The manager Pool implementation mode
    • Interface Design Interaction Mode
    • ...

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

Four basic elements of the design pattern

Pattern Name: Description mode, easy to communicate, archive

Problem: Describes where to apply the pattern

Solution: Describes a design's constituent elements, not for special cases

Consequence: The results and tradeoffs of applying this pattern

Four, using the way of TDD design to implement the plural class complex

The steps are as follows:

1, write to calculate the complex number class complex, divides into subtraction four kinds of situation.

public class Complex {

Private double m;

private double N;

Public Complex (double m,double n) {

THIS.M = m;

THIS.N = n;

}

Public String Add (Complex b) {

Complex x = new Complex (m + b.m, n + b.n);

System.out.println ("a" + "+" + "B" + "=" + x);

Return "true";

}

Public String minus (Complex b) {

Complex x = new Complex (M-B.M, N-B.N);

System.out.println ("a" + "-" + "B" + "=" + x);

Return "true";

}

Public String Multiply (Complex b) {

Complex x = new Complex (M * b.m-n * B.N, M*B.N + n * b.m);

System.out.println ("a" + "*" + "B" + "=" + x);

Return "true";

}

Public String Divide (Complex b) {

Double d = math.sqrt (B.M * b.m) + math.sqrt (B.N * B.N);

Complex x = new Complex ((M * b.m + N * b.n)/D,math.round ((M * b.n-n * b.m)/d));

System.out.println ("a" + "/" + "B" + "=" + x);

Return "true";

}

Public String toString () {

String str = "";

if (n>0)

str = "(" + M + "+" + N + "I" + ")";

if (n==0)

str = "(" + M + ")";

if (n<0)

str = "(" + M + n + "I" + ")";

return str;

}

}

2, write the Complexdemo class, pass in the real and imaginary parts of A and b two complex numbers, call the complex class for calculation.

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.