java 一个java文件如何从另一个java文件调用方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43350522/
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
How can one java file call methods from another java file?
提问by Brian Quinones
How do you call a method from a different class (file) in java?
你如何在java中从不同的类(文件)调用方法?
Are objects required? Or is there a 3rd way to make a merge of documents for java? Can we use a simple method call of is there a proper way to call new methods?
是否需要对象?或者是否有第三种方法来合并 Java 文档?我们可以使用简单的方法调用吗?是否有正确的方法来调用新方法?
回答by KOUSIK MANDAL
Your question is not clear to me, as far as I understand you want to call a method of another java file(I assume another java class).
你的问题我不清楚,据我所知你想调用另一个java文件的方法(我假设另一个java类)。
So consider you have java files A.java and B.java. So you have definitely two classes A and B.
因此,请考虑您有 Java 文件 A.java 和 B.java。所以你肯定有两个类 A 和 B。
Now if you want to call a method of B class from A class you need to do;
现在如果你想从 A 类调用 B 类的方法,你需要做;
- Make the method of B class public (or public static)
- Create a object of B class in A (or if method is static this step is not required)
- Using that object(in case of static user class name) call the method
- 将B类的方法设为public(或public static)
- 在 A 中创建 B 类的对象(或者如果方法是静态的,则不需要此步骤)
- 使用该对象(在静态用户类名称的情况下)调用该方法
Take a look,
看一看,
? Non-static method:
? 非静态方法:
B.java
B.java
class B{
public void myMethod(){
//do stuff
}
}
A.java
一个.java
class A{
public void anotherMethod()
{
B b=new B();
b.myMethod(); //calling B class's method
}
}
? STATIC method:
? 静态方法:
B.java
B.java
class B{
public static void myMethod(){
//do stuff
}
}
A.java
一个.java
class A{
public void anotherMethod()
{
B.myMethod(); //calling B class's method
}
}
回答by tanginaMoBobo
you can try packaging your class
你可以尝试打包你的课程
using package com.yourwebsite;
at the very start of your class and above import statements
使用package com.yourwebsite;
劈头类及以上的导入语句
then at the cmd type javac -d . YourClass.java
然后在 cmd 类型 javac -d . YourClass.java
then you can import it on the next class that you are trying to create
然后您可以将它导入到您尝试创建的下一个类中
to import it use import com.yourwebsite.YourClass;
导入它使用 import com.yourwebsite.YourClass;
note that your package doesn't allow wild card symbol so you must use the full name of your class
请注意,您的包不允许使用通配符,因此您必须使用类的全名