Tuesday, 27 November 2018

Java - Constructors

Constructor can be used to initialize the instance variables of the class and make some tasks when the time of object creation.

 Classname and constructor name must be equal.
Constructor will be called by run time when you create the object.
If the class doesn’t have constructor, runtime supplies default constructor.
If you add parameterized constructor, you must add empty constructor, if you create object without parameter.


class A
{
int a;
   A(int c)
         {
         a=c;
         }
   void print(int x) // called function // formal parameters
         {
              System.out.println(x);
              System.out.println(“a:”+a);
   }
   public static void main(String arg[])
         {
              A ob=new A(100);
              int x=200;
              ob.print(x); // caller // Actual parameters.
              A ob1=new A(200);
              ob1.print(300);
         }
}
O.P
200
100
300
200
In above program, ob,ob1 are the objects and ob,ob1 will have “a” separately.
Listen, “a” is printed from print() without using object.
It means when you create the object or calling the method by using object, the object will be passed as implicit parameter to the constructor or method.
Within instance methods and constructors, the object can be used as “this” keyword. It is optional. The “this” keyword may or may not be used to access the members of class within same class.

Formal parameters will have memory when actual sends the value.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.