Constructor in Java:
In Java, a constructor is a special method that is used to initialize objects of a class. Constructors have the same name as the class and no return type. Here are some key characteristics of constructors in Java:
[access modifier] className([parameter list]) {
// code to be executed
}
Here is an example of a simple constructor in Java:
public class Example {
int value;
public Example() {
value = 10;
}
public Example(int num) {
value = num;
}
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example(20);
System.out.println("Value of obj1 is: " + obj1.value);
System.out.println("Value of obj2 is: " + obj2.value);
}
}
In this example, we define a class called Example with two constructors: one that takes no arguments and sets the value of value to 10, and another that takes an integer argument and sets the value of value to the argument. We then create two objects of the Example class using the two constructors and print their respective value variables. The output of this program would be:
Value of obj1 is: 10
Value of obj2 is: 20
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.