Java 0 Basics Day12 Simple application of Java class

Source: Internet
Author: User

As the saying goes, good practice, so in addition to the theoretical knowledge of solid, more important is to practice more, so as to master the core technology.

Today we use the class we just learned to practice, the goal is to complete the task of chopping hands in the previous article.

Our product class is ready, the code re-listed, here add an overloaded method, about overloading here not too much introduction, later will be specialized article introduction, here it as a common method is good, mainly used to compare two goods are equal, If you are unfamiliar with the code, you can return to the previous article.

Here's the way to introduce the correct use posture of Java annotations. Annotations are text that is inserted in the middle of the source code to describe the code and will not be compiled and executed. The code is not only for compiling, but also for reading, so it is necessary to write enough comments, so as to ensure that in the future, I look back at the time of writing the broken Code of what the ghost, if you write the code of thought also recorded, it is more convenient for their later comparison.

There are three main ways to annotate in Java:

1. Single-line comment, using//

2. Multi-line comments, using the/* code */

3. Documentation comments, using the/** code */This format is designed to facilitate the Javadoc program to automatically generate documents. Here do not introduce, and then a special article to do the explanation.

/*goods Class
Mainly used to record commodity information, and provide access to product information methods
*/
Public classgoods{
instance fields for storing commodity informationPrivateString title= ""; Private Doubleprice=0.0; PrivateString link = "";
  
Constructor 1 PublicGoods (String Atitle,Doubleaprice,string ALink) {Title=Atitle; Price=Aprice; Link=ALink; }//Constructor 2 PublicGoods (String Atitle,DoubleAprice) {Title=Atitle; Price=Aprice; Link= "Www.baidu.com"; }//Constructor 3 PublicGoods (DoubleAprice) { Price=Aprice; Title= "Goods"; Link= "Www.baidu.com"; }//Fetch product title PublicString GetTitle () {returntitle; }//Fetch commodity price Public DoubleGetPrice () {returnPrice ; }//Fetch product link PublicString GetLink () {returnlink; }//Set item title Public voidSettitle (String atitle) {title=Atitle; }//Set up commodity prices Public voidSetprice (DoubleAprice) { Price=Aprice; }//Set up product links Public voidSetlink (String aLink) {link=ALink; }//Output commodity information Public voidprint () {System.out.println ("Title:" +title+ "Price:" +price+ "link:" +link); }

Overloaded Equals Judgment method
@Override
public boolean equals (Object obj) {
return super.equals (obj);
}
}

Such a note, the function of this class is very clear, people will know what you want to do a blind operation, of course, if each use of class to the source of the class to view, it is indeed inconvenient, so there is javadoc such a tool, here because there is no introduction, so first not to use.

Next, we need a shopping cart to store the goods. Because only need to manage a shopping cart, so the budget class is not written first, otherwise it is too much fuss.

 Packagepers.frank.test;/*** Cart class * Shopping cart class for managing commodity and budget information * provides methods for adding items, getting budgets, revising budgets, etc.*/ Public classCart {//instance Domaingoods[] Goodslist =NewGOODS[20];//List of items, because there is no introduction to the list and collection, so first use the array storage, first assume you do not buy more than 20 items    intGoodsnum = 0;//Number of goods    DoubleBudget = 0.0;//Budget    Doubletotalprices = 0.0;//Current Product price//constructor Function     PublicCart (Doubleabudget) {Budget=Abudget; }    //Get product price     Public Doublegettotalprices () {returntotalprices; }    //Get Budget     Public DoubleGetbudget () {returnbudget; }    //Modify Budget     Public voidSetbudget (Doubleabudget) {Budget=Abudget; }    //add goods, budget enough to return true, not enough to return false     Public Booleanaddgoods (Goods agoods) {//judge the budget first        if(Totalprices + agoods.getprice () >budget) {            return false; }        //budget is sufficient to add//iterate through an array to find where the element is null        inti = 0;  for(; i < goodslist.length; i++){            if(Goodslist[i] = =NULL) {Goodslist[i]=Agoods; Break; }        }        if(i = =goodslist.length)return false; Totalprices= Totalprices +Agoods.getprice (); Goodsnum++; return true; }//traverse the product information in the shopping cart     Public voidshowgoodslist () {System.out.println ("Number of items in cart:" + goodsnum + "Total Merchandise:" +totalprices);  for(Goods a:goodslist) {if(A = =NULL)Continue;        A.print (); }    }}

There's not much in the code that needs to be introduced, and the notes are written in detail. The classes that describe and use the data are already built, and then you just need to use them.

 Public classtest{ Public Static voidMain (string[] args) {DoubleBudget = 20000;//BudgetCart Mycart =NewCart (budget);//instantiate a shopping cart object//Create an array of product objectsgoods[] Goodslist =NewGoods[3]; goodslist[0] =NewGoods ("Goodsa", 10000, "Link1"); goodslist[1] =NewGoods ("GOODSB", 6000, "Link2"); goodslist[2] =NewGoods ("GOODSC", 6000, "Link3"); //Cycle Add Items         for(inti = 0; i < goodslist.length; i++){            if(Mycart.addgoods (goodslist[i]) = =true){                //Add SuccessSYSTEM.OUT.PRINTLN ("Product added successfully! Title: "+ goodslist[i].gettitle () +" Price: "+ goodslist[i].getprice () +" link: "+Goodslist[i].getlink ()); }Else {                //Add failedSYSTEM.OUT.PRINTLN ("Product add failed! Current budget: "+ mycart.getbudget () +" Current Product Total Price: "+ mycart.gettotalprices () +" Product prices to add: "+Goodslist[i].getprice ());  Break; }        }        //Print all product information in your shopping cartmycart.showgoodslist (); }}

The output is as follows:

Product added successfully! Title: Goodsa Price: 10000.0 Link: Link1 product added successfully! Title: GOODSB Price:6000.0 Link: Link2 product add failed! Current budget:20000.0 Current Product: 16000.0 price to add: 6000.0 Shopping Cart Item Quantity:2 Total Merchandise: 16000.0TITLE:GOODSA Price: 10000.0 Link:link1title:goodsB Price:6000.0 link:link2

The simple application of our class is written, of course, the class is not perfect, some of the more complex concepts are not introduced, here just to demonstrate the correct use of the class posture and design, do not dwell too much on the details.

As we can see, the main code for testing is actually very small, because we encapsulate the implementation in the class, just use the method in the class according to the rule. This is like building a house, not directly with stone wood pile out, but first processed into bricks and windows, and then build. Using these bricks and Windows is certainly more convenient than using stone wood directly. This is also the convenience of using classes. After we have built the product with the shopping cart class, if some places need to be modified, only need to modify in the corresponding class, as long as the external methods are not changed, then the other code called the code will not need to modify, so that the code can reduce the coupling degree.

At this point, the end of this article, then will introduce more about the class, welcome to continue to pay attention!

Java 0 Basics Day12 Simple application of Java class

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.