join the ap-comp-sci-a course

๐ŸŽ–๏ธfiveable certificate upon completion

โฑ๏ธ 2 min read

๐Ÿ“ย ย 

ap comp sci a

ย โ€ขย 

study guide

ย โ€ขย 

Unit 5

5.2 Constructors


written by

Peter Cao

peter cao

published on september 20, 2020

Last updated on September 20, 2020

The Student Class

Let's start writing our classes by declaring our instance variables and class headers for the Student class:

public class Student { private int gradeLevel; private String name; private int age; private Assignment assignment; }

Now, we need to make our constructor for the student class. The constructor will need to initialize all the above instance variables and allow the client to have the opportunity to set some of the variables to values of their own choosing. For this, we are allowing gradeLevel, name, and age to be set. These will be our constructor parameters with initial values. We will first make the full constructor below and then write the overloaded constructors in Topic 5.9.

public class Student { private int gradeLevel; private String name; private int age; private Assignment assignment; public Student(int gradeLev, String fullName, int ageNum) { gradeLevel = gradeLev; name = fullName; age = ageNum; assignment = null; } }

When a constructor is called, the parameters are local variables, which means that the variables are only defined inside that constructor. Notice how the parameter names are different than the names of the instance variables, but in Topic 5.9 we will learn how to keep both as the same name which is the conventional way to do it.

Fiveable

join more students

create an account on fiveable

Before we move on to the Assignment constructor, if we don't include a constructor for a class, and we try to make a new object, Java will automatically create a default constructor with default values set for the instance variables. Here is a list of them for certain data types:

Default Values By Data Type

The Assignment Constructor

With that, let's do the same with the Assignment class.

public class Assignment { private boolean correctAnswer; public Assignment(boolean answer) { correctAnswer = answer; } }
Fiveable Logo

2550 north lake drive
suite 2
milwaukee, wi 53211

92% of Fiveable students earned a 3 or higher on their 2020 AP Exams.

*apยฎ and advanced placementยฎ are registered trademarks of the college board, which was not involved in the production of, and does not endorse, this product.

ยฉ fiveable 2020 | all rights reserved.