Saturday, 31 October 2015

Object

2. OBJECT:
An Object represents state (instance variables) and behaviour (methods).
Each Object made from a class can have its own values for the instance variables of that class.        We can create n number of objects for same class.
Creating your first object:
Reqt:  
a.       a class for the type of object u want to use.
b.      Another class to test your new class where you put main().
Tester class:
Tries out the methods and variables of your new object class type.
Let’s start with  a popular Example specified in Head First Java.
The Guessing Game:
It involves a game object,3 player object.
Game generates a random number between 0-9.The three players try to guess it.
Logic:
1.GameLauncherClass --- where the appn starts.It has main()
2. In main(), a GuessGame object is created and its startGame() called
3. startGame() --- where the entire game playsout.
It creates three players, then thinks of random number. It then asks each player to guess, checks the result and either prints out the information about the winner or ask them to guess again.
 
Implementation:
Below are the  screen shots of the above example.
In below screens u may observer this
Math.random()*10 – aimed to provide random numbers


 
player class:
 
GameLauncher class:
Output:
 
Over here we have created three objects for player class(p1,p2,p3) and one object for GuessGame class(game).
 
This ends the basics of object. In My next post we’ll discuss on Encapsulation.
 

No comments:

Post a Comment