Java 从另一个班级调用一个班级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19809739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a Class From another class
提问by Sagar
I want to call class2from class1but class2doesn't have a mainfunction to refer to like Class2.main(args);
我想从class1调用class2但class2没有一个main函数来引用Class2.main(args);
回答by Juned Ahsan
Simply create an instance of Class2
and call the desired method.
只需创建一个实例Class2
并调用所需的方法。
Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/
回答by Nathan
Class2 class2 = new Class2();
Instead of calling the main, perhaps you should call individual methods where and when you need them.
也许您应该在需要的地方和时间调用各个方法,而不是调用 main。
回答by Ankit Rustagi
If your class2 looks like this having static members
如果您的 class2 看起来像这样具有静态成员
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
回答by RamonBoza
Suposse you have
假设你有
Class1
1类
public class Class1 {
//Your class code above
}
Class2
2级
public class Class2 {
}
and then you can use Class2 in different ways.
然后您可以以不同的方式使用 Class2。
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 Class2Imagine this is your class2.
Class2 中的静态方法想象一下这是您的 class2。
public class Class2 {
public static void doSomething(){
}
}
from class1 you can use doSomething from Class2 whenever you want
从 class1 您可以随时使用 Class2 中的 doSomething
public class Class1 {
public void loginAs(String username, String password)
{
Class2.doSomething();
//your actual code
}
}
回答by Upendra
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
首先在 class1 中创建一个 class2 的对象,然后使用该对象调用 class2 的任何函数,例如在 class1 中写入
class2 obj= new class2();
obj.thefunctioname(args);