wellnwill Marathahalli Bangalore

Methods


Methods describes the functionality or behavior of an object. In method, we write set of instructions to achieve a task.


Type of Methods

  • Instance Method
  • Static Method

Instance Methods

The method defined in a class without static keyword and which is only accessible through the Object of the class are called Instance method or non-static method.

We cannot use non-static variable inside static method directly but with the help of object reference we can use.

Static Methods

The method defined in a class with static keyword is known as static method. If we have static variable then it is good to create static method because to call static method object reference is not required.

We can call static methods in two ways:

  • By using class name.
  • By using the reference.

Methods Parameters

Methods parameters are also known as method arguments. These are the local variables.

There are two types of parameters.

  • Formal Argument
  • Actual Argument

Formal Argument

The arguments which are used while method declaration.

Actual Argument

The arguments which are used while method call.


Compile time mapping

At compile time when compile read the statement add (1, 2), it will check whether add() method with two int parameter is present or not. This is known as compile time mapping

int add(int a, int b)
{
 return a+b;
}
int z=add(1,2); //method calling
class Bulb
{
  int watt;
  float price;
  boolean state;
  static String cname;
  void modifyState()
  {
    if(state==true)
    {
       state=false;
     }
    else 
	{
      state=true;
     }
  }

  static void modifyName(String n)
   {
    cname=n;
    }
 }

class Test154
{
 public static void main(String args[])
 {
  Bulb b1=new Bulb();
  System.out.println("state:"+b1.state);
  // calling non static method through object reference
  b1.modifyState(); 
  System.out.println("state:"+b1.state);
  }
}


class Test0154
{
 public static void main(String args[])
 {
  Bulb b1=new Bulb();
  System.out.println("cname:"+b1.cname); 
  b1.modifyName("Wipro");      // calling static method through object reference
  System.out.println("cname:"+b1.cname);
  Bulb b2=null;
  b2.modifyName("Bosch");      // calling static method through the reference which contains null
  Bulb.modifyName("Sunlight"); // calling static method through class name
  System.out.println("cname:"+b2.cname);
 }
}


Footer with Map