In this tutorial, we will write a constructor program in java. Before that, you should have knowledge on the following topic in Java.
Constructor program in Java
Basic Example for displaying the default values in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class Employee { int id; String name; int age; //Method for Displaying default values void display() { System.out.println(id + " " + name + " " + age); } public static void main(String args[]) { //creating objects Employee e1 = new Employee(); Employee e2 = new Employee(); e1.display(); e2.display(); } } |
Output:
0 null 0
0 null 0
Example of Parameterized Constructor in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public class Employee { int id; String name; int age; //parameterized constructor Employee(int i, String n, int a) { id = i; name = n; age = a; } //display the values void display() { System.out.println(id + " " + name + " " + age); } public static void main(String args[]) { //creating objects and passing values Employee e1 = new Employee(101, "John", 30); Employee e2 = new Employee(105, "Ron", 32); //calling display method e1.display(); e2.display(); } } |
Output:
101 John 30
105 Ron 32