Writing classes

AP Computer Science A · Unit 3: Classes

Writing classes notes

Fact-checked by a second, independent AI review.

Overview of writing Java classes: define fields, create methods and constructors, instantiate objects, and use encapsulation to manage state.

Class and Object
A class is a blueprint; objects are instances with their own state defined by fields.
Fields and Encapsulation
Fields hold data; mark them private and provide public methods to access them (getters/setters) to protect state.
Constructors
Special methods to create objects; initialize fields; use this() to call another constructor if needed.
Methods
Define behavior with public methods; include parameters, return values, and use this to refer to the current object.
This Keyword and Parameter Naming
Use this to distinguish instance fields from parameters when names collide; good naming reduces confusion.

Remember it: Got a class? Think: fields are the objects’ memory, methods are their actions, constructors build their life.

Exam tip: Examiners reward correct constructor usage, clear encapsulation with private fields and public accessors, and precise use of this to reference current object.

Syllabus checklist

  • Writing classes: core ideas
  • Terms and typical exam questions for "Classes" in AP Computer Science A (Java
  • College Board)

Practice questions

  1. 1. Which keyword creates a new object of a class in Java?

    Answer checked

    Show answer

    Answer: new. The new keyword allocates memory and calls a constructor to create a new object.

  2. 2. In the Point class, what is the value of new Point(3,4).getX() if getX() returns x?

    Answer checked

    Show answer

    Answer: 3. The constructor assigns x=3, so getX() returns 3.

  3. 3. A constructor can be inherited from a superclass: True or False?

    Answer checked

    Show answer

    Answer: False. Constructors are not inherited in Java; you must define them in each class.

  4. 4. Use ____ to refer to the current object inside a class.

    Answer checked

    Show answer

    Answer: this. The keyword this refers to the current instance.

  5. 5. In Java, an int field with no initializer has value ____ by default.

    Answer checked

    Show answer

    Answer: 0. Numeric primitive fields default to 0 when not explicitly initialized.

Practise writing classes as a game

Hearts, combos, streaks and an AI tutor that explains every answer. Start free.

Start free

More from Unit 3: Classes