Java Guide for Dummies
By Mr. Saeed Idris Hasan
Java is built on classes. Consider a class as a collection of things. For example, lets assume that we create a class of drawing room. What does a drawing room have It has a TV, sofa set, lights, audio set, decoration peices, phone. OK so lets assume that. Now you have a collection which is called DrawingRoom with the elements we just mentioned. Now you want to use the elements mentioned (Java term is defined) in our collection DrawingRoom. So for that we need to mention the methods of doing so, so you will need to mention them in your collection DrawingRoom (so this is going to be functions, in Java you refer to them as methods). OK so you may have a method which mentions how to use the TV, switch it on/off and change channels, and same things for the other elements. OK, so what do we have now
Java Equivalent:
public DrawingRoom()
{
// This is called a constructor. It has the same name as the
// class, and gets invoked(called) automatically when the
// class is created/initiated. Usually you will use this
// for initilization(Depends the way you use it).
}
public void switchOnTV()
{
// mention steps to switch on the TV
}
public void switchOffTV()
{
// mention steps to switch off the TV
}
//Define other methods also
...
...
...
} // End of class declaration DrawingRoom
Now we have the drawing room (DrawingRoom), what do we next... Well we need to build it (or create it). So you need to create DrawingRoom now. How do you do that? Well here's the Java code to do the same
| DrawingRoom | myDrawingRoom = | new | DrawingRoom(); |
| 1 | 2 | 3 | 4 |
1 » Class name, for which
the instance is to be created.
2 » Your object name (variable name) for the class defined
3 » "new" is an
operator which creates object instances. It allocates memory
4 » "DrawingRoom()" indicates that you want to
create an object for DrawingRoom based upon the DrawingRoom() constructor
method you have defined in the class.
So you have created an object now. You have your own drawing room (myDrawingRoom). So you want to watch TV. Well switch it on first. How do u do that?
myDrawingRoom.switchOnTV();
Viola! Check it out. TV is switched on.
Mind you, you have to have all Java code within a class's method. Code can just not hang around. The last two lines of code we talked about, should be part of some method. A little secret, when you work with Java look at it from real life's prespective, and you will get it.