简体   繁体   English

如何调用静态类中存在的方法?

[英]How do I call a method which is present inside a static class?

I'm very new to Java programming and I have a doubt. 我是Java编程的新手,我对此表示怀疑。

I have a program like this: 我有一个这样的程序:

class A {

  static final class B {

       public int addMe() {
       }

  }

}

how do I call the method addMe ? 如何调用方法addMe

When I do ABaddme() I get an error. 当我执行ABaddme() ,出现错误。

addme() is an instance method of the inner class B. So you need a B instance to be able to call it: addme()是内部类B的实例方法。因此,您需要一个B实例才能调用它:

A.B b = new A.B();
b.addme();

Your addMe() method is not static, so you can't call it without B class instances: 您的addMe()方法不是静态的,因此如果没有B类实例,就无法调用它:

A.B b = new A.B();
b.addMe();

Typical java inner class (without static) can be initialized only inside the class it is declared in. A static inner class is actually a normal class, visible to any other class in the program, but declared in other class' file. 典型的Java内部类(无静态)只能在声明它的类内部进行初始化。静态内部类实际上是普通类,对于程序中的任何其他类都是可见的,但在其他类的文件中声明。

You have to instantiate the static class B and call the method or mark the method itself as static. 您必须实例化静态类B并调用该方法或将该方法本身标记为静态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Mockito和Junit模拟静态方法中存在的void方法调用? - How to Mock the void method call which is present inside static method using Mockito and Junit? 如何对在 AndroidViewModel class 内部进行 retrofit 调用的方法进行单元测试? - How can I do unit testing of a method which is making retrofit call inside of AndroidViewModel class? 如何在非静态方法中从另一个类调用非静态方法? (java) - How do I call a non-static method from another class in a non-static method? (java) 如何指定从哪个类调用方法 - How do i specify which class to call a method from 如何从另一个 class 内部调用 onItemClick 方法? - How do I call the onItemClick method from inside another class? 如何在windowslistener方法内调用JFrame(类本身)? - How do I call the JFrame (the class itself) inside a windowslistener method? 如何执行在类中声明的函数公共方法,而该类又在私有方法中? - How do I execute the function public method declared inside a class which is in turn inside a private method? 如何从最终类调用静态方法到主类? - How do I call a static method from final class into main class? 如何在同一个类中的方法内部正确调用方法? - How do I properly call a method inside a method inside the same class? java - 如何在一个类中的方法内进行循环以调用另一个类中的另一种方法n Java? - How do I make a loop inside a method in one class to call on another method in another class n Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM