开发者

How to call a method from a static class in another class?

开发者 https://www.devze.com 2023-02-18 02:36 出处:网络
I have a method \"b(Class g)\" in a static class \"a\" so myclass.java contains... public static class a{

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

}


Your method b needs an argument of type Class 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.


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.

a a1 = new a();
a1.b(SomeClass.class);

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. Calling b(); 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 method b(Class g) to be static. i.e.

public static class a{

     static public void b(Class g){
     ....
     }

}

To get a better understanding of static nested class, read this

0

精彩评论

暂无评论...
验证码 换一张
取 消