[!INDEX]
- Def.- special + primary purpose.
- five Points ( default, same, return, overload, invoke)
- Default argument ct , test class obj. access instance var i.
- Above code with NO ARGUMENT CT(), compiler wont make.
- parametrized ct(), above code with no arguent + argument ct calling
- instantiate vs initialization
1. Definition- one line ,3 punch + primary purpose
[!NOTE]
- constructor is a special type of method that is automatically called when an object of a class is instantiated.
- Its primary purpose is to initialize the newly created object.
- if user create any constructor java will not create default constructor.
2. five Points ( default, same, return, overload, invoke)
[!NOTE]
- if user create any constructor java will not create default constructor.
- same name as class
- no return type
- can be overload
- invoke as object create
[!MA]
- one ct to another ct = we have same name dont overload yourself coz we cant return to home and if you die , you wont invoke .
3. Default argument ct , test class obj. access instance var i.
public class Test {
int i; // Instance variable 'i' of type int
public static void main(String[] args) {
Test t = new Test(); // Creating an instance of Test
System.out.println(t.i); // Accessing and printing the value of 'i'
}
}
4. Above code with NO ARGUMENT CT(), compiler wont make.
public class Test {
int i; // Instance variable 'i' of type int
// Constructor D_017Test (default constructor)
Test() {
// Default constructor body (empty in this case)
}
public static void main(String[] args) {
Test t = new Test(); // Create instance of Test using the default constructor
System.out.println(t.i); // Printing values of 'i' 0
}
}
5. parametrized ct(), above code with no arguent + argument ct calling
class Test {
// Parameterized constructor
Test(String name) {
System.out.println("right way");
System.out.println(name);
}
public static void main(String[] args) {
Test t = new Test(); // This line will cause an error
Test t1 = new Test("Book"); // This line will work correctly
}
}
6. instantiate vs initialization
[!NOTE]
Instantiation - refers to the process of creating an instance (i.e., an object) of a class.
new Test() instantiates an object of the Test class.
Initialization - refers to the process of assigning a starting value to variables or instance fields, either explicitly by the coder or automatically (in the case of default values).