如何从另一个类的静态类中调用方法?
我在静态类“a”中有一个方法“b(Class g)”,
所以 myclass.java 包含...
public static class a{
public void b(Class g){
....
}
}
比同一个 myclass.java 中的另一个方法
public void c(){
if(...){}
else{
b(); //i want to call b but i get an error asking me to create the method
}
I have a method "b(Class g)" in a static class "a"
so
myclass.java contains...
public static class a{
public void b(Class g){
....
}
}
than another method in the same myclass.java
public void c(){
if(...){}
else{
b(); //i want to call b but i get an error asking me to create the method
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的方法
b
需要一个Class
类型的参数,这就是它抱怨的原因。更新
你还有一个奇怪的类声明
public static class a
根据Java 类声明规范
并非所有修饰符都适用于所有类型的类声明……
访问修饰符 static 仅适用于成员类
,这意味着您您的公共类声明中有错误的静态修饰符。首先将顶级类声明更改为
public class a
,然后查看它的行为方式。Your method
b
needs an argument of typeClass
that's why it is complaining.Update
You also have a strange class declaration
public static class a
As per Java specification on Class declaration
Not all modifiers are applicable to all kinds of class declarations......
The access modifier static pertains only to member classes
which means you have wrong static modifier in your public class declaration.Change you top level class declaration to
public class a
first and then see how it behaves.有两点需要注意:
1) 尽管内部类 'a' 被声明为静态,但方法
b(Class g)
不是静态的。因此,为了访问类“a”的 b(Class g) 方法,您仍然需要创建“a”的实例,即重要:声明类静态并不会使该类的方法静态。
2) 调用方法
b(Class g)
时,需要传递Class参数。调用不带参数的b();
将导致错误。如果您想调用
b(Class g)
而不创建类“a”的实例,则将方法b(Class g)
标记为静态。即为了更好地理解静态嵌套类,请阅读此
There are two things to note:
1) Even though the inner class 'a' is declared static, the method
b(Class g)
is not static. So in order to access the b(Class g) method of class 'a', you still need to create an instance of 'a' i.e.Important: Declaring a class static doesn't make the methods of that class static.
2) When invoking the method
b(Class g)
, you need to pass the Class argument. Callingb();
with no argument will result in error.If you want to call
b(Class g)
without creating an instance of class 'a', then mark the methodb(Class g)
to be static. i.e.To get a better understanding of static nested class, read this