Tino APCS

Classes in Java

A class in Java is a code blueprint that defines how objects of that type behave, what kind of attributes it contains, and how to create objects of that type.

A class can be used to create many objects of that class type, each of which will keep track of its own attribute values. The same is true for its behaviors. Each object will have the same set of behaviors but each object might run a behavior differently based on its unique attribute values.

For example, if the color and position of two DrawingTool objects is different then calling the drawCircle behavior will produce two different circles.

Three parts of a class

  • In Java, a method is a piece of code that defines a behavior.

    • It is written in the class blueprint. For example, if you told a DrawingTool object to do its drawCircle() behavior, then Java would run the code in the drawCircle() method of the DrawingTool class to produce the circle.
  • A constructor is a method with the same name as the class. Constuctors are used to create and initialize an object.

  • An attribute is a class variable that describes an object. Attributes are used to keep track of an object's state.

To summarize, a class is a blueprint for an object and has three parts:

There is another kind of class that doesn't need all three parts.

In order to run a Java program, you need to write a class that has only one method: a main() method. This is discussed later during this lesson.

Dark Mode

Outline