Incremental Java
Objects are Containers for Instance Variables

Encapsulation

Encapsulation is the idea that you present some information to an object user, while hiding other information away. It is a kind of abstraction.

In particular, you give the user a list of methods they can use for a given class. They create the objects, and use the methods on those objects.

However, hidden away from the user is the implementation. This is how the object does what it does.

In particular, we hide two things from the user:

Instance variables are variables that exist in each object.

You can think of an object as a container for instance variables.

Of course, an object is much more than that. But it's one aspect of an object.

For example, a Rectangle object is likely to contain a height and width variable. Every Rectangle object has these two pieces of information.

Let's declare two Rectangle variables.

  Rectangle rect1, rect2 ;
Recall an object variable can hold an object handle. However, you need to construct an object to get a handle. Right now, I haven't told you how to construct a Rectangle object.

But pretend I have done so. In that case rect1 has its own width and height. Perhaps its width and height are 10 and 10. And perhaps rect2 has width 3 and height 5.

We can ask the height of rect1 and get the answer 10. We can ask the height of rect2 and get the answer 5. Each object has its own instance variables. The class tells you want instance variables each object has.

Class Definition

A class designer writes class definitions. A class definition contains the following information. Let's write out a partial class definition, leaving out the method bodies.
public class Rectangle 
{
   // Instance variables
   private int height, width ;  

   // Method Signatures
   public void setWidth( int newWidth ) ;
   public void setHeight( int newHeight ) ;
   public int getWidth() ;
   public int getHeight() ;
   public int getPerimeter() ;
   public int getArea() ;
   public boolean isSquare() ;
}
You'll notice there's a special word, private, in front of the declaration int height, width. This is to prevent object users from accessing the instance variables directly.

You'll notice there's a special word, public, in front each of the method signatures. This means that the methods are accessible by the object user.

You'll also notice that each method signature ends in a semicolon. This is the only part of the class definition that's not the way it is in true Java code. We'll see how it really looks soon enough.

This class definition must be in a file called Rectangle.java. Remember that the name of the file must be the name of the class, plus a .java extension.

Recall that the class designer writes the class definition. You are beginning to see how a class is designed.