What is a constructor?
java
Student s = new Student("Alice", 11); // constructor runs here
Constructor rules
Writing a constructor
java
public class Student {
private String name;
private int grade;
private double gpa;
// Constructor
public Student(String name, int grade, double gpa) {
this.name = name; // assign parameter to instance variable
this.grade = grade;
this.gpa = gpa;
}
}
No-argument constructor
java
public class Student {
private String name;
private int grade;
private double gpa;
// No-argument constructor
public Student() {
name = "Unknown";
grade = 9;
gpa = 0.0;
}
}
Student s = new Student(); // uses default values
Overloaded constructors
java
public class Rectangle {
private double width;
private double height;
// No-arg constructor — default values
public Rectangle() {
width = 1.0;
height = 1.0;
}
// One-arg constructor — square
public Rectangle(double side) {
width = side;
height = side;
}
// Two-arg constructor — custom dimensions
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
}
// All three work:
Rectangle r1 = new Rectangle(); // 1.0 × 1.0
Rectangle r2 = new Rectangle(5.0); // 5.0 × 5.0
Rectangle r3 = new Rectangle(3.0, 7.0); // 3.0 × 7.0
The default constructor
java
public class Point {
private int x;
private int y;
// No constructor written — Java provides one automatically
}
Point p = new Point(); // x = 0, y = 0
java
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
// Point p = new Point(); // COMPILE ERROR — no no-arg constructor!
Point p = new Point(3, 5); // works
Constructor with validation
java
public class Student {
private String name;
private int grade;
private double gpa;
public Student(String name, int grade, double gpa) {
this.name = name;
// Validate grade is 9-12
if (grade >= 9 && grade <= 12) {
this.grade = grade;
} else {
this.grade = 9; // default if invalid
}
// Validate GPA is 0.0-4.0
if (gpa >= 0.0 && gpa <= 4.0) {
this.gpa = gpa;
} else {
this.gpa = 0.0;
}
}
}
What happens during object creation
java
Student s = new Student("Alice", 11, 3.8);
Complete example with trace
java
public class Dog {
private String name;
private int age;
public Dog(String name) {
this.name = name;
this.age = 0; // all dogs start at age 0
}
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " (age " + age + ")";
}
}
Dog d1 = new Dog("Max"); // name="Max", age=0
Dog d2 = new Dog("Bella", 3); // name="Bella", age=3
System.out.println(d1); // "Max (age 0)"
System.out.println(d2); // "Bella (age 3)"
AP Exam Tips
- •
- •
- •
- •
- •
Common Mistakes
- •
- •
- •
- •