Constructor
Constructor:
Definition:
A constructor is a special method called when an object is created to initialize its attributes.
Explanation:
Constructors ensure proper initialization of an object's state when it's instantiated.
Example:
class Person {
String name;
Person(String n) {
name = n;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person("Darga");
System.out.println("Name: " + person.name); // Output:
Name: Darga
}
}
Comments
Post a Comment