ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

ECLIPSE IDE - Creating Additional JAVA Methods for an ArrayList Class Implementation

Updated on February 28, 2014

In the Previous Tutorial........

The previous tutorial,"ECLIPSE IDE Tutorials - Creating add() and remove() Methods For Objects in Lists"covered the creation of two methods required for our hypothetical car rental agency.

In this tutorial we will create new methods:

carCheckOut(), carCheckIn() - cars are rented and returned. Methods to associate a car with a company rental must be kept up to date.

The "test first" Approach: Describe the Test

As in our other tutorials we will be following the "test first" methodology. So we have to ask ourselves what exactly our test case should do. The objective will be to check out (rent) several vehicles and then process the returns. With each action we will need to perform some test to indicate that the action was correctly performed. For example, if we rent a car (check it out) it should show up as rented. If a car is returned (checked in) then is show be available for rental.

So the test program should look something like:

  • check out, test that the result is appropriate and repeat this one additional time
  • check in, test that the result is appropriate and the repeat as well.


Methods for Rental & Return: carCheckOut() & carCheckIn()

The methods that we will next create are method for car rental and return. One test case will contain testing for both methods. One should alwys sit down and sketch is some sort of pseudo code or bullets to describe the functionality of the method which is to be implemented. The methods we are creating here are not exotic, but they are the first methods which will use a JAVA programmatic feature (i.e. the if.....then.....else construct). So it is a little bit more of a challenge to implement and writing down the requirements is in order.

Program Functionality: carCheckOut

For renting a car there are a couple of considerations for the method being implemented. A number of main points we need to consider:

In checking a car out:

  • car cannot be checked out if it is already rented - the checkout should fail
  • we have to update the car's record to indicated who has rented it - if the checkout succeeds
  • feedback should be given in either case

In terms of coding:

  • check out that this (meaning current object car) is not rented
  • if not rented update to reflect that this company (reflected by the company name field in the billing address record) has rented the car.and let the calling method know it worked
  • otherwise let the calling method know it failed.

In programming terms:the method is going to return some information to the caller. "Success or "failure" is generally indicated as a Boolean, true or false.

The check out method needs information about both the current car object and the intended renter indicated in the current billing address object (the company name)


The Method Signature for carCheckOut()

From the information above, we arrive at something which is formally know as a method signature.

In our case:

  • the access method will be public
  • the method returns an indication of success failure, Boolean
  • both car and billing information is need for functionality

resulting in the method signature:

public boolean carCheckOut(Car c, BillingAddress ba);

Coding the carCheckoutTest() Method

We now begin coding the test with our initial statement for the definition of the method.

public void carCheckOutTest();

next we call our previously created method which creates the car and billing address objects:

populateArrays();

the following four lines are added to add to our lists:

crr1.addCar(c1);

crr1.addCar(c2);

crr1.addBillingAddress(ba1);

crr1.addBillingAddress(ba2);

Our next statement:

assertEquals("Error in car rental", crr1.carCheckOut(c1, ba1));

The first argument to the assertEquals is just a string which will be displayed if the checkout fails. Note that is represent a JUnit common practice, perform some statement then have the result evaluated by an assert statement either assertTrue() or assertFalse() as we will see in a bit.

assertEquals("Starbucks", c1.getBillingAddress().getCompanyName());

Since the assert equals did not fail, we proceed to verify that the renter's name was set appropriately.

Now if we try to check out the car again, the method will return false.. Thus the assertFalse() statement in which the call to carCheckOut() is the second argument, will succeed.

assertFalse("Car already rented", crr1.carCheckOut(c1,ba2));

Now, we will look at the check in method.

assertTrue("car check in failed", crr1.carCheckIn(c1));

Note that the method carCheckIn takes only one argument. That is because to check in a car we do not really need to know who the rented was. Form a practical sense we know the car is available. In a programming sense we will be blanking out any information about the renter in the car object information.

assertFalse("Car was checked in before", crr1.carCheckIn(c1));

Sometime the assertFalse statement confuses, so consider what is happening in this statement very carefully. The previous statement check in the car. so this check in attempt will return false. Since the check in returned false, the assertFalse statement will succeed.

assertFalse("Car not previously rented", crr1.carCheckIn(c2));

Our final test is to try to check in a vehicle which had not been rented. Again, we use assertFalse which will succeed due to the fact that the check in returned false.

The code for this test is illustrated in the snapshot.

Method "stubs" are Created Using ECLIPSE "quick fix"

Sine our test method was created before either carCheckIn() or carCheckOut() were defined we let "quick fix" add this method stubs.
Sine our test method was created before either carCheckIn() or carCheckOut() were defined we let "quick fix" add this method stubs.
We take the suggestion from"quick fix" to create a method.
We take the suggestion from"quick fix" to create a method.

Code for the carCheckOutTest() Method

Creating the carCheckIn() and carCheckOut() Methods

Now we will create the actual methods. We go to the source folder and select out program file.

We will look at the coding of the carCheckOut() method first.

The first line is the method signature:

public boolean carCheckOut(Car c1, BillingAddress ba1) {

The method has type access method of public. It will return either a value of true or false, hence we indicate the return type as Boolean.

The method depends upon having information about both cars (the item being check out) and the renter (represented by the company name field in the billing address). So the method needs these two arguments.

The next statement is an example of an if....then....else. For those reader who may be unfamiliar with the statement what follows is a s short explanation.If you are familiar with the concepts proceed to the next section where we will dissect this code.

if (c1.getBillingAddress() == null) {
c1.setBillingAddress(ba1);
return true;
}
else
return false;

This is the first time we have seen an if statement. The pseudo code for this can be stated as::

if ( a condition being tested is true) {

perform all of these action statements included between the curly braces, otherwise do nothing and continue on with whatever follows the braces, in this case the else.

}

else <--- execute the statement which follows an else is executed if the condition in the if statement is false.

The if...then..else... Statement Explained

if (c1.getBillingAddress() == null) {

There are several things to look at here. Note that (==) is an indication of a comparison taking place. The term null means "empty" or "no value. This would be true in the case where the car was not rented. So the condition being satified would make the next statement make sense. It performs the action to say "this car is rented by this company

c1.setBillingAddress(ba1);

return true; }

After associating the car with it renter we return true. Otherwise we take the else branch and return false indicated in the next two lines.

else
return false;

The snapshot illustrates the completed code.

The carCheckOut() Method Code

carCheckOut method illustrates the first use of it...then..else programming logic
carCheckOut method illustrates the first use of it...then..else programming logic

The carCheckIn() Method

The carCheckIn() method is very similar to this one so we will keep the explantion here to a minimum.

public boolean carCheckIn(Car c1) {

The preceding is the method signature. Only the car object need be referred to.
if (c1.getBillingAddress()!= null) {

The condition here tests whether the car has been rented. The (=!) means "not equal" as a comparison. This could only happen if the car was rented.


c1.setBillingAddress(null);

return true;
}

The preceding statement happen if the car is being returned. The name field is made null (empty) and the method returns true.


else
return false;

If the name was null in the expression. It means that the car was not rented so checking it in
is an error, so we return false.

The code for the carCheckIn() method follows.

The carCheckIn() Method Code

For a check in we expect the value to not be null. We set to null the renter information.
For a check in we expect the value to not be null. We set to null the renter information.

Wrap Up and What's Next

What we covered in this tutorial is the creation of two new methods the carCheckOut() and the carCheckIn() method.

We tried to indicate a way to sketching out the functionality and how we arrive at what the code will look like.

New terms and concepts included: (==) meaning comparison equals in contrast to (=) assignment, (!=) not equals, the if....then...else.... program structure, null, a new term method signature.

What's next is continuing with create new methods for our car rental agency.

getAvailableCars(),- we must know what cars are available for rental. Having a handy list let's both the rental agency and the potential customer know what their options are.

getUnavalibleCars(),- cars may be unavailable for reasons other than their rental (e.g. repair, servicing)

getCarsForBillingAddress() - for the billing department (and other uses) there is a need to know what cars are rented to what company.

That's all till next time!

Was This Tutorial Complete, Concise, and Helpful?

5 out of 5 stars from 1 rating of Please rate the value of this tutorial to you!
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)