Tuesday, 27 November 2018

Java - Methods

Methods are behavior of an object. It is used to change the state of class (Instance variables).

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.modifier] returntype methodName()
{
//code
}
Example
void sum() // default modifier method
{
}

The method can be called by using an object only, that object can be known as invoking object.

Instance method can use instance variables and static variables of the class.
Instance methods will have invoking object as implicit parameter.

No comments:

Post a Comment

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