Sunday 9 June 2013

Objects and Classes

Objects

In object-oriented programming we create software objects that model real world objects. Software objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behavior with methods. A method is a function associated with an object.
Definition: An object is a software bundle of variables and related methods.

Classes

In object-oriented software, it’s possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. A class is a software blueprint for objects. A class is used to manufacture or create objects. The class declares the instance variables necessary to contain the state of every object. The class would also declare and provide implementations for the instance methods necessary to operate on the state of the object. Definition: A class is a blueprint that defines the variables and the methods common to all objects of a certain kind.
  1. public class CoffeeCup {
  2. private int innerCoffee = 0;
  3. public void addCoffee(int amount) { // a method
  4. innerCoffee += amount;
  5. }
  6. public int releaseOneSip(int sipSize) {
  7. int sip = sipSize;
  8. if (innerCoffee < sipSize) {
  9. sip = innerCoffee;
  10. }
  11. innerCoffee -= sip;
  12. return sip;
  13. }
  14. public int spillEntireContents() {
  15. int all = innerCoffee;
  16. innerCoffee = 0;
  17. return all;
  18. }
  19. }


EmoticonEmoticon