Computer Science Researcher • Educator • Programming Instructor
A constructor is a special method that runs automatically when an object is created. It is used to set initial values for object variables.
class Car {
Car() {
System.out.println("A new car object has been created!");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
}
}
The constructor runs immediately after new Car() is called.
class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Khalid", 25);
Student s2 = new Student("Ayesha", 23);
System.out.println(s1.name + " - " + s1.age);
System.out.println(s2.name + " - " + s2.age);
}
}
This constructor allows setting values when creating the object.
this Keyword
class Book {
String title;
double price;
Book(String title, double price) {
this.title = title;
this.price = price;
}
}
public class Main {
public static void main(String[] args) {
Book b = new Book("Java Made Easy", 49.99);
System.out.println(b.title + " - $" + b.price);
}
}
this.title refers to the class variable,
while title on the right side is the parameter.
class Player {
String name;
int score;
Player() {
name = "Unknown";
score = 0;
}
Player(String n) {
name = n;
score = 0;
}
Player(String n, int s) {
name = n;
score = s;
}
}
public class Main {
public static void main(String[] args) {
Player p1 = new Player();
Player p2 = new Player("Ali");
Player p3 = new Player("Sara", 100);
System.out.println(p1.name + " - " + p1.score);
System.out.println(p2.name + " - " + p2.score);
System.out.println(p3.name + " - " + p3.score);
}
}
Java picks the constructor based on the number of arguments.
class Engine {
int horsepower;
Engine(int hp) {
horsepower = hp;
}
}
class Car {
String model;
Engine engine;
Car(String m, int hp) {
model = m;
engine = new Engine(hp);
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car("Corolla", 180);
System.out.println(c.model);
System.out.println("Engine HP: " + c.engine.horsepower);
}
}
class User {
String username;
User(String name) {
username = name;
welcome();
}
void welcome() {
System.out.println("Welcome, " + username + "!");
}
}
public class Main {
public static void main(String[] args) {
User u = new User("Khalid");
}
}
The method welcome() is automatically called when the object is created.
class BankAccount {
String owner;
double balance;
BankAccount(String ownerName, double initialDeposit) {
owner = ownerName;
balance = initialDeposit;
}
void show() {
System.out.println(owner + "'s balance: $" + balance);
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Khalid", 2500);
acc.show();
}
}
this keyword helps avoid naming conflicts.