Introduction to Java Packaging ideas

Source: Internet
Author: User

First, Introduction

  This chapter upgrades the crossword puzzle game 1.0 in the first article , and then gives the reader a brief introduction to Some of the knowledge and implementation ideas of the packaging concept in JAVA.

Ii. Introduction to the concept of encapsulation

 Three basic features are proposed in object-oriented programming: encapsulation, inheritance and polymorphism. Among them, encapsulation is the basis of inheritance and polymorphism. If the meaning of encapsulation is not well understood, then the learning of inheritance and polymorphism cannot be discussed. Therefore, in order to better understand the encapsulation idea, we will solve the following problems (2.1):

    • What is encapsulation?

    • Why do we need encapsulation?

    • What are the characteristics of encapsulation?

    • How is encapsulation implemented?

The idea of encapsulation, from its origins, has been a long time. As early as Aristotle's time, he had writings on types. And this type is the origin of the encapsulation idea. In other words, an abstraction of an object with similar behavior and attributes is divided into a group, and the merging process of this object is called encapsulation.

We just need to pull out their shared parts for use. In JAVA It is called the encapsulated module, which is typical of class.

The advantage of this idea is that, on the basis of the problem-based description, the feasible methodological guiding ideology is put forward. The question of how to do it. The core of his thinking is splitting up and splitting a big problem into a lot of small problems, but here's one thing to note: This is not an unrestricted split, his purpose is just to make the problem more efficient to solve. So, the degree to which we divide is that we can solve him by studying and studying in a short time.

Since the idea of encapsulation is just a matter of breaking the big question, then we can divide the programmer into two categories- the creator of the encapsulated object and the consumer of the encapsulated object.

For the purpose of division of labor, the purpose of the user is only to collect a variety of classes used to achieve rapid application development, what they need is the function of these things rather than the implementation. But the creator is the opposite.

This creates a contradiction in whether the object in the class can be accessed arbitrarily. The answer is negative.

In any relationship, it is important to have a boundary that is respected by all the aspects involved in the relationship. If all the members of the class are available to anything, then the user of the class can do anything to the class without being constrained. This is one of the most important reasons for the bug that many programs are using-the user's input is not legal, and the creation of the program does not respond to a strong refusal (deny any illegal input).

Why do we need a strong rejection mechanism? In practice, we will encounter various, if we choose to ignore him, often will have disastrous consequences, this is not uncommon examples of neglect. such as the warning of earthquakes and the development of serious illnesses. So, I have a desire to have a mechanism to solve any problems encountered, which is called over-optimization in programming. However, it is virtually impossible and difficult to complete. Because the concept of the problem is too broad and involves specific situations. So, when we don't know the situation, we should set the situation and draw the scope. The establishment of the scope, on behalf of the refusal, what can be entered, what can not. This is also the idea of encapsulation, another important concept - to establish the scope.

Therefore, the creator needs to make hidden and restricted access to some parts of the code.

In this case, access control hides the parts that the consumer should not touch- This is part of the internal operation for the data type, but is not part of the interface that the consumer needs to solve a particular problem. (In other words, this is only a service to the user, because they can easily see that things are important to him and which can be overlooked.) )

-- class

As a result,JAVA has made public,private(private), protected in defining internal boundaries. (Protection) The division of these three definitions.

These access-specific words determine who can be used by what is defined immediately after.

    • publicprivate: Private part, Like his own private garden, no one can access this element except for the type creator and the internal method of the type. (For this purpose, he ends up with the return

    • protected: Protection type, This is dedicated to inheritance, later in the introduction. He and private

Finally, there is a default form of access, called Package access. If you do not use any of the above to access the specified word, he will play a role, the class can access other class members in the same package, but outside of this scope, its members in addition to the creator of the class and its own internal methods can be accessed, the rest will be rejected, plainly speaking is the larger version of the Private type.

Immediately after, our module has been designed according to the access rights, then there will be some demand -- We hope that our creation should be a useful code unit, he can call repeatedly, and this call the simplest way is to create it. This approach is also called reuse. Although, in fact, sometimes this kind of reuse will be unsatisfactory.

Because of the new module, you can have any number of other objects of any type in any way. However, the composition of the way there are static and dynamic two aspects. Where static is called a combination, dynamic is called aggregation.

Because reuse can bring great flexibility. The member objects of the new module are also usually declared privateso that theuser cannot access them and the bugis reduced. This also allows you to modify them without interfering with the main program code. At that time, it can also be modified while the program is running. From the feature of reuse, it is much like the concept of inheritance, but he is simpler and smaller. Therefore, when building a new module, it is preferable to use it, and the concept of inheritance and its implementation are discussed later.

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/852001/201512/852001-20151212204133028-1433448481. JPG "style=" border:0px;margin-left:auto;margin-right:auto; "/>

Figure 2.1 Introduction to packaging ideas

Third, build their own applications

3.1 Requirements:

Change the 1.0to make a crossword puzzle game with a different level 2.0: Match the user input letters, and the whole pair indicates the user wins.

3.2Concrete implementation of encapsulation idea

3.2 as shown, we need the following several modules:

    • Requires an interface that can read and write to the console.

    • A letter generator is required.

    • A match is required that matches the user input data with the generator generating letters (the matching device has a mechanism to determine how many letters the user has matched correctly).

    • A loop counter is required (to alert the user to the number of times left and count the number of cycles).

One of the things we need to change is the random number generator in 1.0, which changes it to a letter producer. and the comparison module in the 1.0, separately mentioned out of the package, change its function as a matching device.

Program Data structure:

1.char type array input: Used to save user guessing alphabetic data.

2.char type array temp: Used to hold letters generated by the letter generator.

3, array of type int result: Used to save the judgment result. (the array contains two elements, the first element is used to hold the number of letters that are fully guessed, and the second element is used to hold the user guessing the number of letters (the characters are correct but the position is incorrect).)

4,int type variable num: Stores the total number of times the user has played the game.

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/852001/201512/852001-20151212204437434-105799214. JPG "style=" border:0px;margin-left:auto;margin-right:auto; "/>

Figure 3.2 puzzle game 2.0

3.3Algorithmic Flow

650) this.width=650; "Src=" http://images2015.cnblogs.com/blog/852001/201512/852001-20151212204557434-1589522028. JPG "style=" border:0px;margin-left:auto;margin-right:auto; "/>

Iv. Concrete Implementation
package abcgame;import java.util.scanner;public class abcgame {/** *  Charades 2.0 *  @param  input   used to save user guessing alphabetic data  *  @param  temp    Used to save letter generator generated letters  *  @param  result  to save judgement  *  @param  num      Total number of users who have played games  */public static void main (String[] args)  {//  main program directory char[]  input = null;char[] temp = generate ();int[] result = new  int[2];int num = 0; Scanner s = new scanner (system.in); System.out.println ("You are welcome to participate in the game!" "); System.out.println ("The game begins! Please enter five different letters: (exit--exit, your health value is "+ (temp.length*100) +", each error is deducted 10 points) "); while (true) {string inputstr =  S.next (). Trim (). toUpperCase (); if ("EXIT". Equals (Inputstr)) {System.out.println ("Thank you for participating, goodbye!"). "); break;} Input =inputstr.tochararray ();for  (int k = 0;k < input.length;k++) {for   (int u = 0;u < input.length;u++) {if (K != u && input[k]  == input[u]) {System.out.print ("Please start again and enter the correct five-bit different letters!! "); System.exit (0);//program ends normally. }}}result = check (temp,input);if  (result[0] == temp.length) {System.out.println (" Congratulations, you guessed it! Your score is "+ (temp.length*100-num*10)"; else {num++; System.out.println ("You guessed to" +result[1]+ "characters, where" +result[0]+ "characters are correct!) "); SYSTEM.OUT.PRINTLN ("Your health is left" + (temp.length*100-num*10)); if ((temp.length*100-num*10)  == 0) { System.out.println ("Hope next time, thank you for participating!" "); System.exit (0);}} S.close ();} /** *  Letter Match  *  @param  letters  26-Letter storage  *  @param  temp      save randomly generated letters  *  @param  flags    to store letter locations selected.  *  @param  index    How many locations to save randomly generated  */private static char[]  Generate ()  {//  letter Generator char[] letters={' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ',' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z '}; char[] temp =new char[5];boolean[]  flags = new boolean[letters.length];for  (int i = 0;i<temp.length;i + +) {int index;do{index =  (int) (Math.random () * (Letters.length));} while (Flags[index]);//Determine whether the generation of letters repeats temp[i] = letters[index];flags[index] = true;} Return temp;} /** *  Letter Match  *  @param  input   user guessing alphabetic data  *  @param  temp     Letter Generator-generated letters  *  @param  result  for saving judgment results  */private static int[]  check (char[] temp, char[] input)  {//  letter Match Int[] result = new  int[2];for  (int i = 0;i < input.length;i++) {for  (int j=0;j  < temp.length;j++) {if (Input[i] == temp[j]) {  //Determines whether the user entered the letter correctly result[1]++;          &nbSp; if (i==j) {             // Determine if the correct letter entered by the user is in the correct position Result[0]++;break;}}} Return result;}}

  


This article is from the "10960391" blog, please be sure to keep this source http://10970391.blog.51cto.com/10960391/1722347

Introduction to Java Packaging ideas

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.