Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Constructors
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
We mentioned constructors when we discussed declaring classes and we will visit this topic again later. For now, let's discuss what a constructor is and what it does. If a class is a description of a possible object, then the constructor is what functions to create the object of the class.
Constructors are often used with values called parameters that are stored in the data portion of the object that is created. Take a look at the program below. String parameterOne is the parameter of the constructor. The name of the constructor has to match the name of the class.
ConstructorsExample.java
package exlcode;
public class ConstructorsExample {
private String exampleVariable;
// this is the Default constructor of the class
// that has no parameters
public ConstructorsExample(){
}
// this is the constructor of the class
// that takes in one parameter
public ConstructorsExample(String parameterOne) {
// this prints exampleVariable
System.out.println(parameterOne);
}
public static void main(String[] args) {
// this will be explained in Unit 8
ConstructorsExample constructorsExample = new ConstructorsExample("Hello World!");
}
}
Each class has at least one constructor. In the case that the programmer does not write a constructor definition, Java will produce a default constructor for that class. The default constructor will only perform the following basics: allocate memory and initialize instance variables. If we want more to happen when an object is created, we can include one or more constructors in the class definition. When declaring a constructor, remember that a constructor does not have any return type, not even void, so the header of the constructor should look something like this: public ClassName().