Intern
Mis on konstruktor Java's?
sobes.tech AI
Vastus AI-lt
This is a special class method used for object initialization. It is called automatically when creating a new instance of the class using the new operator.
Main properties:
- Has the same name as the class.
- Does not return any value (not even
void). - Can have parameters used to pass initial values to the object's fields.
- Can be overloaded (have different number or types of parameters).
- If the constructor is not explicitly declared, the compiler provides a default constructor (without arguments), which initializes primitive type fields with default values and reference types with
null.
Example:
class MyClass {
int value;
String name;
// Constructor with parameters
public MyClass(int value, String name) {
this.value = value;
this.name = name;
}
// No-argument constructor
public MyClass() {
this.value = 0;
this.name = "Default";
}
}
// Creating objects
MyClass obj1 = new MyClass(10, "Example"); // Call constructor with parameters
MyClass obj2 = new MyClass(); // Call constructor without parameters