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

- 733
- 3
- 11
- 16
-
4You should go through a basic tutorial.. – Maroun Nov 06 '13 at 10:36
-
this is bad. tests should be self-contained and independent. – ddavison Nov 06 '13 at 16:20
5 Answers
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
}
}

- 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
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

- 5,539
- 12
- 39
- 70
Simply create an instance of Class2
and call the desired method.
Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/

- 67,789
- 12
- 98
- 136
-
-
@SagarT You are correct, you need to create an instance from where you need to call. – Juned Ahsan Nov 06 '13 at 10:43
Class2 class2 = new Class2();
Instead of calling the main, perhaps you should call individual methods where and when you need them.
-
-
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
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);

- 29
- 6