请注意:这是一个实验,而不是真实情况。我想了解更多,因此我问这个问题。
<小时/> 我有一个类ABC
,带有静态方法 method()
:
public class ABC
{
public static void method(){
System.out.println("ABC class");
}
}
<小时/>
我有一个类 DEF
,带有非静态方法 method()
:
public class DEF
{
public void method(){
System.out.println("DEF class");
}
}
<小时/>
最后,我有一个包含以下代码的 GHI
类:
public class GHI
{
public static void main(String args[])
{
ABC.method();
DEF ABC = new DEF();
ABC.method();
}
}
<小时/>
输出为:
<小时/> 我知道输出的原因。ABC class
DEF class
我的问题是:在这种情况下,我们有一个类的对象,其名称与另一个类的名称相似,那么我们如何调用该类的具有相同名称的方法作为对象的方法?
说白了:这种情况下,如何调用ABC类的静态方法method
?
最佳答案
In this situation, how can I call the static method method of
ABC
class?
您可以创建 ABC.method()
的静态导入
(假设 ABC
类位于 com 中) .package
package)并调用它。
import static com.package.ABC.method;
public class GHI {
public static void main(String args[]) {
method(); // calling the static ABC.method()
DEF ABC = new DEF();
method(); // calling the static ABC.method
ABC.method(); //calling the instance method()
}
}
这样您就可以区分static method()
和实例method()
(在DEF
中定义)。
关于java - 当我们有一个同名的对象时,引用一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36334664/