Explain the Initialization of an object using a sample program segment.
Advertisements
Question
Explain the Initialization of an object using a sample program segment.
Code Writing
Explain
Advertisements
Solution
Initialization of an Object is the process of assigning initial values to the data members (instance variables) of an object. In Java, an object can be initialized using a constructor, a method or direct assignment through a reference variable.
A constructor is commonly used to initialize an object because it is automatically called when the object is created.
class Student
{
int rollNo;
String name;
Student(int r, String n)
{
rollNo = r;
name = n;
}
void display()
{
System.out.println("Roll No: " + rollNo);
System.out.println("Name: " + name);
}
public static void main(String args[])
{
Student s = new Student(101, "Rahul");
s.display();
}
}
shaalaa.com
Is there an error in this question or solution?
