What are Objects, Classes, and Methods, and what does Object Orientation mean?

Java is an Object Oriented language, and understanding Object Orientation (OO) is the backbone to understanding Java.

For many years, the advanced computer languages, amongst them C, were written with a structured approach, and were known as structured languages. Structured languages would group up a bunch of actions, and tie them together into a function. Then, whenever they needed a certain action to be used, they would call on that function to do it for them. The reason for using this approach, was in order to help shorten the amount of code. Lets look for example at the action game Prince of Persia. (Games are easiest to illustrate with, as you can see and explain exactly what is happening. I picked this game because it is relatively simple, although if you were to use a more complex game like Diablo or Alice, then you would see the need for Object Orientation even more.) There are hundreds of soldiers that the prince has to fight with, and many of the soldiers do exactly the same thing. Imagine writing the same code for each soldier. That's no problem, you say, I'll just cut and paste the code one hundred times, using "control C" and "control V". Yes it is a problem. Suppose you finish writing the code for the game, and your boss tells you that you have to change one detail in the soldiers. You're going to have to find each soldier in the code, and change it. Of course you're going to end up missing one, and your program is not going to work well. Suppose he tells you to change all of the green soldiers. You're really going to be messed up. This is true if you find an error, or for some other reason need to restructure the whole game. The maintenance will become a nightmare. Imagine if this wouldn't be a game, but a major online store or banking system. Also, imagine how much memory the code for hundreds of soldiers would be. Therefore, the programming language creators started structured language, where everything is a function of actions. Therefore, in your Prince of Persia code, you only need to write the actions of swinging the sword, jumping, attacking the prince, etc. once, tie each action in a function and for each soldier call the same function. When the prince reaches the second floor (for example), you will write the code for a soldier to come, and call each function that the soldier needs. That would save you a lot of coding.
Wait a second, you say, you can't do that. Not every soldier attacks in exactly the same way. The yellow soldiers are fast at blocking, the tall guard in the seventh level waits for you to make the first move, etc. If you write the same code for each one, then all of the soldiers would be the same, and if you write complete different code, then your stuck with your old problem of maintenance. After all, there's usually only one small difference between one soldier and the next. No problem, said the structured programming people, we can fix that. We will have one function use most of the code of a different function. For example the prince reaches the second floor, and there's a blue soldier. You write all of the action for the blue, to attack, etc. The code to attack take up lines 150-200. You reach the third floor (line 250), and there's another blue soldier. You tell this second blue soldier to just borrow all of the code of the first soldier. You write in your code, goto line 150, continue till line 200, and then come back here to line 260, instead of continuing at line 201. You reach the fourth floor, and there's a yellow soldier. You write in your code goto line 150, but since the yellow soldiers are better blockers, only use lines 150-180, and when you get to line 180 come back to our code. And even when the prince reaches more different soldiers, he can borrow some of the functions of one soldier, and some of the next. That way everything works out well. The basic function code is never repeated, while we can still be flexible.

However, people noticed that there were two major problems. The first problem was that using a structured language caused many bugs to occur, and made it harder to fix. For example, lets say the green soldier borrowed some code from the yellow soldier on line 270, and some code from the red soldier on line 400, and adds some of its own. However, when the prince goes to fight the green soldier, the green soldier doesn't fight back. Why? You read and reread the added code, and it seems fine. Then you have to figure out, maybe when I went back and had a goto earlier line, there was an error on the earlier line. But, why would it work there and not work here? Hence, you would have a hard time finding where the cause of the error came from. Also, let's say you decide to take out the red soldier on line 400. Then without you realizing it, the code for the green soldier will not work. The code will say, use a function from the red soldier at line 400, and there is no red soldier at line 400. You'll have a pointer that is now pointing to something that isn't there anymore. However, the main problem was that writing actions and grouping them into functions does not mimic real life, and if you want to write real lifelike games, then this is a must. In the game, you wrote the code as a series of actions, where one action causes the next action. You filled the action with data as necessary. Think of the Prince of Persia game as we described it until now. When the prince, reaches the second floor, then the soldier walks, then the soldier strikes, etc. You fill in the data of the soldier (what he looks like) just as the side, and the main objective in the code is which action to do next. Life is not a series of actions. When we bump into our friend John, it's not like John never existed, and now he comes into play as a series of actions. John was always there as a person, that also does certain actions. That bothered the programming people, because if you want to write really complicated games, then you can't just have groups of actions. You would have to have everything as objects, where you create objects and use them, and each object will contain the actions that are necessary inside the object. Hence Object Orientation was born. (I don't think that it was the need for having more realistic computer games that drove for the creation of Object Orientation, but lets face it, that is what really counts.)

Object orientation means that everything in the program is an object, mimicking real life. In reality by a car, for example, there doesn't exist a function to drive, and whenever any car needs to it "borrows" and uses that function. Rather, there are many objects of cars, and each one has its own individual function to drive. An object like a car is composed of methods, like driving, braking, opening and locking a door, yelling at you when your seatbelt's off, etc, and data like the color, make, model, etc. When you mimic this in a computer object, you also, create methods and data. The data of an object is called fields or variables, and are usually lower cased. The methods ( seen in the code as methodName()) contain actions, like openDoor(), drive(), and inside each method are instructions on how to do that. Also, one method may divide itself into smaller methods, and call each method one after another. For example, method openDoor() might be made up of and call smaller methods like unlockDoor(), pushDoorOpen(), moveSeatBelt(), checkIfNightTime(), and then a turnLightsOn(), if it is night time. This helps you write the code, by breaking up everything into smaller methods. If you are writing the code for a car, and you need the car to open its door, you can write the words openDoor(), and fill in how to do it later. Whenever you need the door to open, all it takes is one method call, and you can call it whenever and wherever you want. In the Prince of Persia game, you can have for the prince a method called jump(), swingSword(), and walkForward(). Method walkForward(), will check what is in front of the Prince. If there is a plank, then it will call method walk(), if there is nothing it will call method fall(), and if there is a wall it will call method wallAhead(). This makes it very easy to break up a large problem into smaller bits. When you put all of the pieces together you're able to ignore the details of the methods on how they work, and when you work on each method's details, you can hide the big picture. This is necessary, as some games and programs are extremely complicated, and it is impossible to see the big picture and all of the details at the same time. Another example of this in the Prince of Persia game is the object called soldier. In that soldier class you will put methods and data. Some of the methods are attackPrince(), jump(), wasHit(), die(), etc, and some of the data will be color, amount of time that he can be hit, etc. This data that we will call canBeHit will be a int, or number, variable. When the soldier starts fighting, the variable data canBeHit may start out as 5. In that case, when you start the code for that soldier, you might tell the main program, see how many hits he has, and put triangles for each hit that he can receive. Every time the soldier is hit by the prince, the soldier's method of wasHit() is called. This method will start by calling a smaller method of showHit() that will show on the screen the soldier being hit. Then it will subtract the hit variable by one. Then it will check if canBeHit equals zero. If it does it will call the method die(), if it doesn't it will call the method weakened(), which it will be that method's job to tell the main program to lessen one of the soldier's triangles. This is just an example, as I am trying to show how one method uses the other methods and data.

There are two terms that seem confusing, and need to be clarified before I explain more: classes and objects. Up until now I have been using these two terms interchangeably, but they are different. A class is the code that you write up. There will be only one soldier class (assuming that all of the soldiers are the same). However, there may be many soldier objects. Each instance of the soldier class is another object. For example, when the prince reaches the tower, your program creates five soldiers to block him and try to kill him. Each one of those soldiers are an object of class soldier. When you fight them, one soldier object might have five hits left, one may have three, and one may be dead. Another example in the real world. There is one class of Toyota Camry. However, there are thousands of Toyota Camry objects, as I am currently driving one, my neighbor has one in his driveway, and I just saw one that got into a crash down the block. Although we're all part of the Toyota Camry class, we each have an independent object. Back to the Prince game. The game has a main class, that runs the game. There is also a prince class and a soldier class. Lets say in the game, when the prince reaches the tower, five soldiers come out (like before). In the main class, you will write code that says if the prince reaches the tower, instantiate (meaning create an instance or Object of) one soldier calling it soldierOne, a second soldier calling it soldierTwo, etc, and tell each one to attack the prince. This helps writing your code in many ways. First of all it helps mimic real life, enabling you better to visualize how to write it. Second, it makes writing the code real easier. I need to only write the code for soldier once, with all of its complicated methods, and whenever I want one, I just tell the main program to create a new object of that soldier, and put it here. I don't need to worry about telling one soldier to now swing at the prince, one soldier to now jump, etc. The program will do that automatically, as I had instructed in the soldier class. Each object of that soldier will follow all of the rules that the soldier class has, all I need to do is tell the main program, put one here, put one here.

Great, you'll say, that helps me to visualize the program better, and I can even see how this will help keep my errors down and make my debugging easier. But, it doesn't help with the problems that you started with. Your program works well if there is only one kind of soldier. Lets say you want there to be different kinds of soldiers, and each one does something slightly different. You're going to have to write many of the same lines of code many times for each different soldier class, and your going to have all of the maintenance problems that you discussed in the beginning. The answer to that is "No", Java and Object Orientation take care of that also. They do it with something known as inheritance. Inheritance means that the child class can inherit, and get everything that is in the parent class automatically. The most well used example is that of a car. Almost every car is similar, with a few exceptions. If you were writing code for a car, you would have methods like openDoor(), drive(), brake(), rollDownWindow(), etc. Lets say that this code has 200 methods, and took 1800 lines of code (not to mention a week). Now, you have to write the code for a convertible. The only difference between a convertible and a regular car is that the convertible's roof can come down. If you had to cut and paste all of the code from the car class, then yes you would have all of the problems. But, you can write in your code I want the class of Convertible to extend and inherit everything from class Car, and automatically class Convertible will have all of the methods and data from class Car. The code for Convertible will have written inside of it only one method, openRoof(), will be only 100 lines of code, but will be able to do all 200 methods of class Car. Even if you need a second car that drives differently you can say that the Car2 extends everything from Car, and write one method called drive(). Since the child class (Class2) extends class Car, it will automatically have all 200 methods. However, since it has one method with the same name as the parent class, the computer will ignore the parent's method of drive(), and only use Car2's new method of drive(). In our Prince game, you can create a class called BadGuy, that has certain methods and data that every single enemy in the game will have. Then you can have one class called Skeleton that will have only the special and different methods that skeleton will have, and one called Soldier, that will have its special methods. Then, both class Skeleton and Soldier will automatically have every method that class BadGuy will have, and whatever they added. You can even make two classes called StupidSoldier and FastSoldier that have minor differences, and have each one inherit from class Soldier, and add their own minor differences. That way, if you have to change a piece, you only need to change it in one place, and every class that depends on that piece will now change. This is somewhat of an oversimplification, but the main purpose of this page is to give an understanding of the topic, and not go into details of how it works.
So far we discussed two ways to have a class relationship. It can be a "stand alone" class that doesn't inherit from any class, or you can have one class inherit from another. Another way, is for one class to contain inside it another class. For example, You can have a Car class, a Wheel class, and a Door class. The Car class will have inside it four Wheel objects, and four Door objects. You can have a FramedWondow Class that will have inside it a few Button classes. You write the code for a Button class, and you tell the FramedWindow to contain that Button by instantiating and placing inside that Button. In these examples, one class has a second class inside it.

I am now going to give a second example of inheritance. In programming, there are many kinds of popup windows, each containing buttons and other stuff, that are needed often. Therefore, Java created them for you automatically, and all that you have to do is instantiate (tell the program, create an object of this kind of window here) them. (See the API section for details.) In Java's graphic package there's a class called Window, that when created pops up a simple window. There are two classes that need everything that Window have, and more; Dialog and Frame.
DIALOG FRAME
Java Dialog Box Java Frame
Class Frame needs whatever Windows has, plus the icon, the ability to add a menu bar, the boxes in the corner to enlarge, make small, and close, etc. Class Dialog only has the icon and the box to close. However, Dialog has something that Frame doesn't, the ability to freeze every other window besides for itself. Therefore, you don't want the Frame to inherit from Dialog because Dialog has the ability to freeze the other windows, and you don't want Dialog to inherit from Frame, because Frame has a whole lot more than Dialog. However, most of the code is exactly the same, and to cut and paste would be wasting a lot of code. The answer is simple. Create a class that has whatever both Frame and Dialog both have in common, and each one will inherit that class and add what they have individually. This is what Java has done for you already, by creating a Window class, and having both Frame and Dialog inherit from Window, and add their individual methods. This is inheritance, as now both Frame and Dialog are really a Window with added features.
Containment would be for class Frame to contain and have inside it other classes. Java has premade classes like Button, Label, TextField. In the following picture, you see a Frame that has Buttons, Labels and TextFields. Just Like a Car has a Door, so too one Java class can have inside it another Java class. And in reality, The Prince of Persia game uses containment, because the main program had inside it both the prince and all of the soldiers. All the Prince of Persia had to do was write create a new soldier here, create a new soldier here, and the main program will now have inside it a new soldier object. Java Frame with Buttons

One last example of inheritance. By Java's premade Frame class, if you hit the little close box in the corner, nothing happens. Java did this so that you can have more control of your Frame, but it is extremely annoying. All that it would have taken Java to do in order to close the Frame would have been to add 5 lines of code, but now you are stuck with a Frame that doesn't close. But not to worry. You can inherit the Frame class, and add those five lines. You can wrote a program that will now be only 10 lines which you can call ClosableFrame, which all that will be in the code is ClosableFrame should inherit everything that is in Frame, but add that when the close box in the corner is hit, the Frame will close, and your new class of ClosableFrame will have everything that its parent Frame class has, plus it will close, with only a few lines of code.