Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Salesforce by (11.9k points)

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.

1 Answer

0 votes
by (32.1k points)

In order to use method1 in class controller2, two approaches are possible:

1. Using Static methods:

You can't use controller2 instance methods

public class controller2 

{

    public static string method2(string parameter1, string parameter2) {

        // put your static code in here            

        return parameter1+parameter2;

    }

    ...

}

Now, in a separate class file, call the method2()

// this is your page controller

public class controller1

{

    ...

    public void method1() {

        string returnValue = controller2.method2('Hi ','there');

    }

}

2. You can create an instance of another class like this:

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');

    }

}

You can also use the following if your methods are in a package with namespace:

string returnValue = mynamespace.controller2.method2();

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...