How to call a method of a class into another class in apex

apex-codeforce.comsalesforce

I want to use a method of a class onto another class.

     eg: public class controller 1{
          public void method 1(){}
      }


     public class controller 2{
         public void method 2() { }     
       } 

I want to use method1 in class controller2.
Please help me to find the solution on it

Best Answer

You can use two approaches:

1.Use Static methods

You cannot use controller2 instance methods here

public class controller2 
{
    public static string method2(string parameter1, string parameter2) {
        // put your static code in here            
        return parameter1+parameter2;
    }
    ...
}

In a separate class file call method2()

// this is your page controller
public class controller1
{
    ...
    public void method1() {
        string returnValue = controller2.method2('Hi ','there');
    }
}

2.Create an instance of the other class

public class controller2 
{
    private int count;
    public controller2(integer c) 
    {
        count = c;
    }

    public string method2(string parameter1, string parameter2) {
        // put your static code in here            
        return parameter1+parameter2+count;
    }
    ...
}

public class controller1
{
    ...
    public void method1() 
    {
        controller2 con2 = new controller2(0);
        string returnValue = con2.method2('Hi ','there');
    }
}

If your methods are in a package with a namespace

string returnValue = mynamespace.controller2.method2();