Introduction to Classes and Objects

I often get asked to explain the difference between a Java class and an object. A common way to describe a Java class is to think of it as a blueprint, cookie cutter, or factory used to create objects with. A class defines the implementation details, the fields and methods to store the state and execute the behavior of objects. In contrast, an object is an instance of a class. There can be one or many object instances for a given class but there is only one class for a given type. A common example of object state is that when you have an ArrayList, the list has a size. The ArrayList also has a certain behavior, to increase by one element and update the list size, when you invoke the add method. The size and contents are the state of an ArrayList, and adding and removing elements is its behavior.

In addition to declaring and implementing the fields and methods, state and behavior, for a object, a class can also define methods that don’t logically belong to a single object instance but that belong to the class type itself. Methods that belong to the class are marked as static. A common example of static methods are those in the Math class. You can’t create a object instance of the Math class, the default constructor is private. Since you can’t instantiate an object, all the methods it declares are invoked at the class level. To invoke the absolute static method made available in the Math class you do so by the following example.

int abs = Math.abs(-10);

Here is how you would access the static PI field in the Math class.

System.out.println(“PI: “+Math.PI);

Technorati Tags: , , , , , ,

Related posts:

  1. Java Five-Oh #2: Static Import
  2. Ruby Mixin Tutorial
  3. Class Loading Error
  4. Reopening Ruby Classes
  5. Class HighLite Calendar
  6. Class HighLite Collections


Leave a Reply