Home »
Java Programs »
Java Class and Object Programs
Java program to implement the parameterized constructor
Learn how to implement the parameterized constructor in Java?
Submitted by Nidhi, on March 21, 2022
Problem statement
In this program, we will create a Sample class and implement a parameterized constructor.
A constructor is a special type of method that initializes data members of the class and instantiates the object.
Source Code
The source code to implement parameterized constructor is given below. The given program is compiled and executed successfully.
// Java program to implement the
// parameterized constructor
class Sample {
int num1;
int num2;
Sample(int n1, int n2) {
num1 = n1;
num2 = n2;
}
void printValues() {
System.out.println("Num1: " + num1);
System.out.println("Num2: " + num2);
}
}
class Main {
public static void main(String args[]) {
Sample obj = new Sample(10, 20);
obj.printValues();
}
}
Output
Num1: 10
Num2: 20
Explanation
In the above program, we created a Sample class and public class Main. The Sample class contains data members num1, num2, and a parameterized constructor, a method printValues(). Here, we initialized data members using the parameterized constructor.
The Main class contains a static method main(). The main() is an entry point for the program. Here, we created object obj and called the printValues() method to print values of data members.
Java Class and Object Programs »