English

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

  1. 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.
  2. Using Methods: An object can be initialized by calling a method that assigns values to its instance variables.
  3. 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?
Chapter 4: Objects - EXERCISE [Page 107]

APPEARS IN

Dheeraj Mehrotra Computer Science [English] Class 12
Chapter 4 Objects
EXERCISE | Q 7. | Page 107
Advertisements
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×