Sunday, September 25, 2016

JAVA Creating Classes and Objects



When trying to store data on something complex that requires lots of variables, maybe of different types (strings, integers, doubles) we need a good way of organizing everything.

For example, if we wanted to write code involved in managing a restaurant we might want to store:

      Strings (name of the restaurant, managers, waiters/waitresses)
     
      Integers (number of employees, number of tables, number of customers)

      Doubles (amount earned, amount spent, supply costs, salary costs)

All of this data may need to be stored in arrays, array lists, or hashmaps. Also, there may be methods created that deal specifically with manipulating and updating this data.

What happens if we want to collect data like this on a whole chain of restaurants?  We can stay organized by using Classes and Objects.

We have seen a few Classes that are built into JAVA, like the String Class and the Math Class.

Objects called strings and integers, etc. use these classes to get access to built-in methods contained in the class, like the string.length method.


We can also create our own Classes for Objects that we want to describe like a restaurant object.


Creating a Class

Class files do not themselves execute methods, or create and manipulate any data, they simply define and initiate methods for objects that can be called in other areas or files of your program.

Step1: Initiate the Class


The following syntax initiates a class called Restaurant: 


public class Restaurant  {


public indicates that anyone can use this Class

Names for classes typically start with a capital letter



Step2: Initiate the Class Field Variables



Field variables or Instance variables are used inside the class by methods you want to create in the class. For the restaurant example, we will create field variables for the following:

name : name of the restaurant , string type

earned: the total amount earned , double type

costs: the total costs incurred , double type


The syntax for initiating these class field variables looks like the following:

public class Restaurant  {

String name;
double earned;
double costs;



Step3: Initiate the Class Methods



Methods created in the class can reference the field variables or create new ones. Two methods are created in the Restaurant Class:

     calculateProfit(double profit) - calculates the total current profit     

     displayEarned() - prints the Restaurant Name and the total amount earned


The complete syntax for the Restaurant Class looks like the following:



public class Restaurant  {

String name;
double earned;
double costs;

//Method to calculate total profit

public void calculateProfit(double profit) {
profit = earned - costs;
return profit;
}

//Get access to println for the method displayEarned



Logic Interface aLogic;
public Restaurant(Logic Interface logic){
aLogic = logic;
}

//Method to print the total earned

public void displayEarned() {
aLogic.println("Total Earned is " + earned);
}

}




Class Concepts


The Classes you create should be general enough that they can be reused, for example the Restaurant Class can be used over and over again for each of the chain restaurants discussed earlier.

The class may interface with either a programmer creating additional code that uses the class, or the end user who may look at the displays and outputs provided from the class. Both of these users should be kept in mind.

Privacy


Field or Instance variables can be set to private as shown in the following syntax to add security and not allow outside programmers or users direct access to them. This is almost always done to ensure that the class and author of the class has total control of how these variables are used. Methods that are only used by the class itself, should also be set to private.



private String name;
private double earned;
private double costs;


JAVA HashMaps


HashMaps implement the Map Interface which stores data using a key and a value pair.  You can think of an array as a map that uses the index locations as the key for each value stored.

When you want to map values to different types of keys, like mapping names to an address, you can use a Map. This way, you can store data that is associated with other data.

The keys used must be unique identifiers for a specific value in a HashMap group. Typically, keys will be strings and the data mapped to the keys will be numerical integers, doubles, etc. The string keys are converted to integer numbers using the "Hash Function." Keys are assigned to integers randomly and stored in a table. To call a value in the HashMap, the key must be provided.


Benefits of HashMap

1) Ability to store data that is associated with other data, ie names and phone numbers
2) Fast Look-Up - must know the key for the value of interest
3) Fast Addition - adding to table without concern of order
4) Fast Subtraction - subtraction of an element not concerned with order


Methods Available in the Map Interface

- add a (key, value) pair - put (K key, V value)
- looks up the value of a specified key - get (key)
- remove elements  - remove(key)
- clear all collection - clear()
- searches for a key, if found returns TRUE -  containsKey(key)
- searches for a value, if found mapped to one or more keys returns TRUE -  containsValue(key)
- checks if the map contains the same elements as another map - equals(map)
- get size of collection - size()
- checks to see if the collection is empty - isEmpty()
- returns a string version of the map - toString()
- return a Set Collection of all keys - keyset ()
- return a Collection of all values - values ()





Initializing a HashMap


When initializing a HashMap it is helpful to use the more basic Map callout for the first collection type - this will help if you want to change the type easily later on, if needed.


Map<String,Integer> newMap = new HashMap<String,Integer>();


Using Methods on a HashMap



The following example stores the number of times a playing card comes up in a game. For example, each time a King of Hearts is turned over, a counter increases by 1 for that type of card. A list of all cards is mapped to the corresponding count for the number of times that card was flipped.  Finally, a list of the (key, value) pairs is printed.  This example will assume a list of card flips has already been loaded into an array called arrayCards.


// Needed import for the HashMap generation


import java.util.*;

Map<String,Integer> newMap = new HashMap<String,Integer>();

for (String card : arrayCards) {

//Determine if the card is already contained in the map as a key
//If it does not currently exist add it with a count of 1
//If it does currently exist add to the current count by 1

if (!newMap.containsKey(card)) {
newMap.put(card,1);
} else {
newMap.put(card,newMap.get(card)+1);
}

}

// Now Iterate over a Set of the HashMap keys to print the key and value pair



Set<String> keys = newMap.keySet();

Iterator <String> itr = keys.iterator();

while(itr.hasNext()) {

String key = itr.next();
int value = newMap.get(key);

Out.println(key + " " + value);

}