16

I want to call class2 from class1 but class2 doesn't have a main function to refer to like Class2.main(args);

Sagar
  • 733
  • 3
  • 11
  • 16

5 Answers5

24

Suposse you have

Class1

public class Class1 {
    //Your class code above
}

Class2

public class Class2 {
}

and then you can use Class2 in different ways.

Class Field

public class Class1{
    private Class2 class2 = new Class2();
}

Method field

public class Class1 {
    public void loginAs(String username, String password)
    {
         Class2 class2 = new Class2();
         class2.invokeSomeMethod();
         //your actual code
    }
}

Static methods from Class2 Imagine this is your class2.

public class Class2 {
     public static void doSomething(){
     }
}

from class1 you can use doSomething from Class2 whenever you want

public class Class1 {
    public void loginAs(String username, String password)
    {
         Class2.doSomething();
         //your actual code
    }
}
RamonBoza
  • 8,898
  • 6
  • 36
  • 48
  • In object oriented books it is usually written that objects exchange between them messages by calling the one the methods of the other. This answer describes the only way it can happen in Java or there are other ways that the message exchange can occur? – Novemberland Mar 18 '19 at 19:45
3

If your class2 looks like this having static members

public class2
{
    static int var = 1;

    public static void myMethod()
    {
      // some code

    }
}

Then you can simply call them like

class2.myMethod();
class2.var = 1;

If you want to access non-static members then you would have to instantiate an object.

class2 object = new class2();
object.myMethod();  // non static method
object.var = 1;     // non static variable
Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
2

Simply create an instance of Class2 and call the desired method.

Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
2
Class2 class2 = new Class2();

Instead of calling the main, perhaps you should call individual methods where and when you need them.

Spotlight
  • 472
  • 1
  • 11
  • 22
Nathan
  • 266
  • 4
  • 16
  • i want the whole Class2 to be called at an instance? What should i do? – Sagar Nov 06 '13 at 10:41
  • You would need to create and call a main method class2.main(args[]); Or call a controller method that deals with the code you wish to execute. class2.controllerMethod(); public class2{ public void controllerMethod(){ // code you wish to execute here } } – Nathan Nov 06 '13 at 11:05
1

First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1

class2 obj= new class2();
obj.thefunctioname(args);
Upendra
  • 29
  • 6