Explain the term Initialization of an Object. How do you do that?
Advertisements
Question
Explain the term Initialization of an Object. How do you do that?
Explain
Advertisements
Solution
- Using a Constructor: A constructor is a special member of a class that is automatically called when an object is created. It is used to initialize the data members of the object.
- Using Methods: An object can be initialized by calling a method that assigns values to its instance variables.
- Using Reference Variables: The data members of an object can be initialized directly using the dot (
.) operator, provided they are accessible.
Example:
class Student
{
int age;
Student(int a)
{
age = a;
}
}
class Main
{
public static void main(String[] args)
{
Student s = new Student(18);
}
}
In the above example, Student is a class, and s is a reference variable. The statement new Student(18) creates an object and calls the constructor, which initialises the instance variable age with the value 18.
shaalaa.com
Is there an error in this question or solution?
