Page 269 - PowerPoint Presentation
P. 269
CAVITE STATE UNIVERSITY
TRECE MARTIRES CITY CAMPUS
Department of Information Technology DCIT 111 - Advanced Programming
Employee1.displayInformation();
Employee2.displayInformation();
Employee3.displayInformation();
OUTPUT:
}
} This is the Constructor, I am created whenever object is created!
This is the Constructor, I am created whenever object is created!
This is the Constructor, I am created whenever object is created!
Account 101 Christian 20000.0
Account 102 Poniente 25000.0
Account 103 Langit 30000.0
// Java program to demonstrate the initialization through constructors
class Employee {
int ID;
String Name;
double Salary;
Employee(int id, String name, double salary) { // parameterized constructor
ID = id;
Name = name;
Salary = salary;
}
void displayInformation() {
System.out.println("Account " + ID + " " + Name + " with salary of " + Salary + " is
created!");
}
}
public class TestEmployee {
public static void main(String[]args) {
Employee Employee1 = new Employee(101, "Christian", 25000.75);
Employee Employee2 = new Employee(102, "Langit", 45000.25);
Employee1.displayInformation();
Employee2.displayInformation();
}
OUTPUT:
} Account 101 Christian with salary of 25000.75 is created!
Account 102 Langit with salary of 45000.25 is created!
Constructors in Java
In Java, a constructor is a block of codes similar to a method. It is called when an
instance of the object is created, and memory is allocated for the object.
It is a special type of method which is used to initialize the object.
When is a Constructor called?
Every time an object is created using new() keyword, at least one constructor is called.
It calls a default constructor.
45