I want to call class2 from class1 but class2 doesn't have a main function to refer to like Class2.main(args);
This question is related to
java
class
selenium
selenium-webdriver
call
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
}
}
Class2 class2 = new Class2();
Instead of calling the main, perhaps you should call individual methods where and when you need them.
Simply create an instance of Class2
and call the desired method.
Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/
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);
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
Source: Stackoverflow.com