Join 150,411 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 954 people online right now. Registration is fast and FREE... Join Now!
No real code to post with this one. This is mainly asking for some info.
The only way I am going to pass my Java class is for me to be able to write programs for it. I am able to make a class, but I can't get my mind around how to use it. I have spent many hours reading tutorials and all, but they all say the same thing to me. If I understood all of it, I wouldn't be here. I need something in plain English that a complete n00b can understand.
What I am looking for is a plain explanation of how to use a class. I am currently working through the various Inventory programs, but without being able to understand I'm not getting anywhere with it. I have to have Java for my degree, even though I may never use it. I would prefer to understand what I am supposed to do. Several have paid for someone to write their programs, but I want to learn.
Thanks for any and all help.
This post has been edited by Trotter: 17 Mar, 2008 - 11:16 AM
A class is an object you can use for accomplishing tasks. Lets say you want a class to work with text files You would create your class.
java
public class TextFiles {
}
Then lets say one of the objectives of your class is to read a text file and return its contents in a string. You could create a method to read the text file. Declare it as a string so it can return what you're looking for.
java
public string ReturnFileContents(string fileName) { //your code for reading the file and returning it }
When you're ready to use it you then need to instantiate it, create an instance of your object so you can access it's properties, methods & events.
java
TextFiles objFiles = new TextFiles();
Now you have created an instance of your object, and it is in memory waiting for you to use it. Now, to access the ReadFileContents value, you would declare a string variable, then set that variable to your method, passing it the file you wish to read
Now fileContents holds the value of the text file you passed the object's ReadFileContents method. Think of a class as an object, in this object are properties, methods & events you wish to use. Doing this in a class prevents you from writing the same code over and over again in multiple places. Put the functionality you want inside your class (object), then when you need it create an instance of it (stored in memory) so you can then access the functionality of it.
Ever see blue prints of a house or a car or a piece of machinery? Blue paper with the whole white lines that tell crafts people how to actually build it? With measurements etc? Think of that as your class definition. The part of code that reads
java
public class Car { private int numWheels = 4; private String color;
public Car(String carColor) { color = carColor; }
public void Drive() { System.out.println("Hey look I am driving my " + color + car!"); } }
It tells you how to build a car right? It says it has 4 wheels and a color and it appears to have the functionality to drive it. This is a map of a car. It tells the program what a car even is. Remember Java has no idea what a car is. Only you do.
The second part is telling the compiler to actually build them. It is like giving the blue print of the car to a builder and say "Create me three cars, one that is red, one that is blue, and one that is green"
How do you tell the compiler to build a car? You do this by saying "Compiler, look up a car, get some space out in memory to hold it and create an 'instance' of it."
You do all these steps by the following lines...
java
// Create an instance of my red cadillac Car mycadillac = new Car("red");
// Create an instance of my blue car Car myferrari = new Car("blue");
// Create an instance of my green car Car mypinto = new Car("green");
Now I have three car objects made. My mechanics have built three cars and told them what color they are. The compiler has gone out and reserved space for three car objects. So I feel a bit crazy today and I want to drive my red car. I do this by using my new car object built for me and calling its drive method to drive it.
java
mycadillac.Drive();
This prints out "Hey look I am driving my red car!". How did it know it was red? Because of the blue print of a car said to use its own color in the phrase for driving a car. Color was something unique to each instance of our cars. The blue car knows its is blue and the green car knows it is green because we told them what color they were when we created their instances.
java
myferrari.Drive();
This will print "Hey look I am driving my blue car!"
So lets say I have a garage to keep my cars in. This might be seen in code as an array of cars. A garage would be the array, each car bay would be a slot in that array and each car would be stored in them. The garage is an array of cars.
java
Car mygarage = new Car[3];
// First slot in garage mygarage[0] = mycadillac;
// Second slot in garage mygarage[1] = myferrari;
// Last slot in garage mygarage[2] = mypinto;
So now using our garage we can drive whatever car is in that bay of the garage.
java
mygarage[2].Drive();
This says take whatever car is in garage bay 3 and call its Drive() method. It will print "Hey look I am driving my green car!"
Understand?
This post has been edited by Martyr2: 17 Mar, 2008 - 11:43 AM
Psych, you had until you popped out "instantiate" and blew my mind. I know what it means, but I couldn't follow it after that. I think the blank () mess with me... I dunno. But it doesn't make sense to me. the " 1. string fileContents = objFiles.ReadFileContents("C:\YourFile.txt");" makes some sense, though.
Martyr, I think you might have struck oil. I was able to follow your illustration all the way through. Now if I can only translate that into a program...
Using what ya'll said, and some examples I found online, I ended up with these:
CODE
// InventoryA program
public class InventoryA // begin InventoryA class {
private static int itemNum[] = new int[3];// number of the item private static String name[] = new String[3]; // name of the item private static int units[] = new int[3]; // quanity of item in stock private static double price[] = new double[3]; // price of item private static int i = 0;
public InventoryA(int _itemNum, String _name, int _units, double _price) // constructor { itemNum[i] = _itemNum; name[i] = _name; units[i] = _units; price[i] = _price; i = i + 1; }
public static double valueOfInventory(double p,int u) { return p*u; }
public static void showInventory() { for(int j=0;j<i;j++) { System.out.println("Product Name : " + name[j]); // print name System.out.println("Item Number : " + itemNum[j]); // print number System.out.println("Number of Units: " + units[j]); // print units System.out.println("Unit Price : " + price[j]); // print price System.out.println("The value of the inventory of " + name[j] + " is = " + valueOfInventory(price[j], units[j]));//call the valueOfInventory() method and display the value } }
} // end class
CODE
public class InventoryMain { public static void main( String[] args) { InventoryA p = new InventoryA(1, "pencils", 12, 0.5); InventoryA q = new InventoryA(2, "Notebooks", 15, 0.5); InventoryA r = new InventoryA(3, "pens", 20, 0.6);
//show inventory InventoryA.showInventory();
} }
They both compiled and seemed to work. Do they look correct?
Psych, you had until you popped out "instantiate" and blew my mind. I know what it means, but I couldn't follow it after that. I think the blank () mess with me... I dunno. But it doesn't make sense to me. the " 1. string fileContents = objFiles.ReadFileContents("C:\YourFile.txt");" makes some sense, though.
I'll take a stab at explaining objects as well. Both Psych and Marty gave good examples of classes in object oriented languages, but I will try to explain WHY we use classes and objects instead of how.
Classes and objects are used for many reasons, here are two.
First, they mimic the way things interact in the real world. I will explain it using the same example you can find at Sun Java Tutorial.
A class in the real world might be all bicycles in the world. Make the distinction... it is not your bike, it is not my bike, it is a type of object or thing. It's abstract. So how do bicycles behave? How do they interact with the rider? What properties do they have? These things are known as class variables and methods. A variable holds a value, while a method performs an action. So I might want my bike to have a color... say String myColor="blue", or I might want to pedal it faster to speed it up... say public void increaseSpeed(int increment), where increaseSpeed is the name of the method and increment is how much faster I might want to go.
When you "instantiate" a class you are in essence buying the bicycle. Until you tell the program to make an object of type bicycle... until you actually get a bicycle and bring it home, you can't ride it, pedal it, observe its color, etc. Likewise the program doesn't do anything to a bicycle until you make one... myBike = new Bicycle(). Now I have an object, a bicycle, my bicycle. you can also make a bicycle yourBike = newBicycle(). Yours can be red, mine can be blue... they each have some of their own properties. They may also share properties known as static final variables or simply "constants." For instances they might share "static final int noWheels = 2" as all bikes have two wheels.
A good game to play, especially if you have an interest in programming outside of just passing a class, is to identify items around you, define their properties, and define how they interact with the world. For instance, I have a stapler on my desk. It has properties such as color, brand name, number of staples. It also has two methods. I can add staples, and I can staple paper. Here is some example code to define the class.
if noStaples > 0 { System.out.println("The paper was stapled."); noStaples--; } else { System.out.println("You are out of staples, please add more"); } }
public void addStaples(int moreStaples){ noStaples+=moreStaples; } }
Explaining the above class, which does not have a constructor (don't need to know this, just wanted to add for correctness).
I made three variables for my stapler. A good class would make all variables private (only accessible by the object itself), but I at least wanted to make the number of staples private. When the stapler is closed up, you don't know how many staples are in it, only the stapler does.
My first method might be called outside the class as myStapler.staplePaper(). If the object myStapler has enough staples, it will tell me that it stapled. If it doesn't have enough staples it tells me to add more. I can do this through myStapler.addStaples(50), which adds 50 staples to the stapler. Well, why don't I just say myStapler.noStaples = 50; to add more staples? For one, the variable is private, this generates a compiler error. Second reason, what happens if my little brother wants to add silly putty to my stapler myStapler.noStaples = "Silly Putty" . This obviously defeats the purpose of the stapler, it wants staples not silly putty. By defining my stapler in this way, I define what are the critical variables to allow it to work and HOW IT INTERACTS WITH THE WORLD.
This leads into the second reason classes are good. They allow code to act in expected ways. It also allows someone to reuse my stapler class without necessarily knowing everything about how a stapler works. They just need to know how to staple paper, and how to reload it with more staples.
Similarly, you don't need to be a mechanical engineer to use a car. To go faster you hit the gas pedal, to slow down you hit the brake, to increase the fuel you stick a fuel nozzle in the gas tank and squeeze (and go broke). Granted you could speed up by wedging the throttle open, you could ruin your brakes by disconnecting the line, you could increase your fuel by drilling a hole in the side of the tank and funneling it in... but there will definately be unintended consequences. The car maker tells you exactly how to perform the tasks on the car and doesn't leave it up to the driver to find their own way to do these things. This is what making a class does.
I hope my analogies help to clarify the benefits of classes in some ways.
This makes sense InventoryA p = new InventoryA(1, "pencils", 12, 0.5);. However the implementation is wonky. First, statics are bad, don't use them in anything other than main.
Judging by the construction, you want your object have have this data: itemNum, name, units, price? Let's start from there. First, you have an inventory and that has items? Your InventoryA is sort of a mashup of the two. Let's focus on the item.
java
class InventoryItem { private int itemNum; private String name; private int units; private double price;
public InventoryItem(int itemNum, String name, int units, double price) { // note, we are assigning the values to this object, no one else this.itemNum = itemNum; this.name = name; this.units = units; this.price = price; }
//We don't need to pass anything, the object alread has this information //public double valueOfInventory(double p,int u) public double getInventoryValue() { return this.price * this.units; }
// again, we can show ourselves public void showInventory() { System.out.println("Product Name : " + name); // print name System.out.println("Item Number : " + itemNum); // print number System.out.println("Number of Units: " + units); // print units System.out.println("Unit Price : " + price); // print price System.out.println("The value of the inventory of " + name + " is = " + getInventoryValue()); } }
Now we have an item. But we want to show all the items, yes? Here's the rest of the code; we'll make InventoryMain also keep our items.
java
public class InventoryMain { // not static, these all belong to the current object! // define the capacity of our item array private int maxItems; // current number of items we have private int itemCount; // the item array, not yet initialized private InventoryItem[] items;
// the constructor public InventoryMain(int maxItems) { this.maxItems = maxItems; // initialize our array this.items = new InventoryItem[maxItems]; this.itemCount = 0; }
// note, this is one less than the InventoryItem constuctor // our main will deteriming the itemNum public void addItem(String name, int units, double price) { // we should check to see if we have max items... that's up to you
// our items start numbering at 1, our array index starts at zero int itemNum = this.itemCount + 1;
// assign the object to the array this.items[this.itemCount] = new InventoryItem(itemNum, name, units, price);
// increment our count this.itemCount++; }
// now we just loop and ask the objects to do the work. public void showInventory() { for(int i=0; i<itemCount; i++) { this.items[i].showInventory(); } }
// this is the only static. Do not make any more. public static void main( String[] args) { // We need an object to process. We'll make instance of this class. // I know, instance is a scarey word. When you get it, all will be clear. InventoryMain pgm = new InventoryMain(10);
// add some items to our InventoryMain object pgm.addItem("pencils", 12, 0.5); pgm.addItem("Notebooks", 15, 0.5); pgm.addItem("pens", 20, 0.6);
// show what we have pgm.showInventory(); } }
There are a number of methods our objects probably want. Our classes should have a number of "get" methods. InventoryItem for it's data in general, InventoryMain for thinks like size and getInventoryItem(int index).
I don't like to give out this much code, but you seem to be just on the edge, kinda, sorta.
They look good to me so far Trotter. If they compile, you should be getting a list of the objects printing out when you run the program. If you see your print lines there when you call showInventory() you are golden.
Except Baavgai is right about the statics...I would drop them since they are not needed for your class in this situation.
This post has been edited by Martyr2: 17 Mar, 2008 - 03:12 PM
I started to rewrite your code from scratch... my way... but I stopped halfway through because you need the practice
EDIT: Well ... the code that was just posted was exactly what I started doing Looks like someone else agrees with me. Again though, for practice, I recommend stating more explicity what your inventory needs to be able to do. Programming is simple. The bulk of my work is writing the pseudocode. With good pseudocode a monkey can do the coding.
Your coding is adequate, but before you ask the question before... please spell out explicity what you need your code to do in plain english.
I don't think your code exhibits class structure as it should, and the style might be ok.
I would tend to implement the code as follows. An inventory class is a collection or array of product classes. When you want to add a new item to the inventory you tell it to create a new product in its main array. The product class would give methods to set and get its 4 variables (price,quantity, itemNO, description). The inventory would contain the functions to loop through the array and print contents, search for items, delete items, sort items, etc.
What you did what in effect blend my two classes into one. This is a programmer's choice and you may do as you wish. Both methods have merits and drawbacks, but the best way to decide where one class ends and another begins is to explicitly define from the start what you want your class to represent and do. I believe as long as you don't wish to do much management on your inventory class, it will suffice. However, if you wanted to start manipulating it much, you might want to break the products into different classes.
If you would please take the time to spell out what you need and want, I will take more time to explain the best way to break your problem down
However, if programming isn't your thing and your program satisfies all given requirements, you might be good to go.
This post has been edited by Steven Smith: 17 Mar, 2008 - 03:16 PM