AP® Computer Science A · Unit 3 · Topic 3.3

The Anatomy of a Class

A class is a blueprint that keeps an object's data (fields) and the code that acts on that data (methods) in one place, built once by a constructor and shared by every method in the class.

A class works because data and behavior belong together. Width and height describe a rectangle, and only methods inside Rectangle should be trusted to use them correctly, so the class keeps the fields private and gives the rest of the program methods like getArea to ask questions about the object without touching its insides directly. That bundling is the whole idea of a class: state and the operations on that state, in one file.

Inside the file, three pieces stack up. At the top sit instance variables, declared once, outside any method, holding the object's state. Below them sits the constructor, a block that runs exactly once per object, at the moment of construction, to set those instance variables to starting values. Below that sit the methods, which run whenever called and can read or change the instance variables because every method in the class can see them. A Rectangle class holds width and height as instance variables, a constructor Rectangle(double w, double h) that assigns them, and a method getArea() that returns width times height.

Each object built from the class gets its own separate copy of the instance variables. Rectangle r1 = new Rectangle(3, 4) and Rectangle r2 = new Rectangle(5, 2) do not share width or height; r1.getArea() and r2.getArea() read different fields entirely. This separation is what makes instance variables different from local variables declared inside a method, which exist only for that one method call. It also sets up the next idea: passing objects to methods hands over a reference to this shared state, not a fresh copy of it.

Key terms

instance variable
A variable declared inside a class but outside any method, holding state that belongs to each object.
constructor
A special block that runs once when an object is created, usually to set its instance variables.
local variable
A variable declared inside a method that exists only while that method call is running.
method
A block of code inside a class that defines behavior, often reading or changing instance variables.

Watch it explained

  1. How it worksHow do instance variables, constructors, and methods stack up inside one class file?
  2. Worked exampleBuild a Rectangle class with width, height, a constructor, and a getArea method.
  3. How it worksHow does every object made from a class get its own copy of the instance variables?
  4. Common mistakeWhy isn't an instance variable the same as a local variable declared inside a method?

Check yourself

Your turn1 of 2
A Rectangle class has a constructor that sets width and height, and a getArea method that returns width·height. Rectangle r = new Rectangle(15, 14); What does r.getArea() return?

End of topic.