Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Class From another class [closed]

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

like image 817
Sagar Avatar asked Nov 06 '13 10:11

Sagar


People also ask

Can you call Main class from another class?

Solution: Though Java doesn't prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to.

How do you call a different class in Java?

To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main.

How do you access the members of a class from another class in Java?

To access the members of a class from other class. First of all, import the class. Create an object of that class. Using this object access, the members of that class.


1 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
    }
}
like image 163
RamonBoza Avatar answered Sep 16 '22 11:09

RamonBoza