英文:
Not able to identify what type of nested class by static method call in java
问题
通常情况下,我们可以通过查看它们的签名来识别所有的类、方法和数据成员。
示例:Math.sqrt(),System.out.println
Math - 类
sqrt - 静态方法
print/println - 实例方法
但无法识别嵌套类的静态方法。
package so;
class Outer {
static String outerVar = "ABC";
class InsInner {
static void show() {
System.out.println("实例内部 " + outerVar);
}
}
static class StaticInner {
static void show() {
System.out.println("静态内部类的静态方法 " + outerVar);
}
}
}
public class NestedClass {
public static void main(String[] args) {
Outer.InsInner.show();
Outer.StaticInner.show();
}
}
为什么静态和非静态类具有相同的约定?
Outer.InsInner.show();
Outer.StaticInner.show();
英文:
Usually, we can identify all the classes, methods & data members by seeing their signatures.
Ex: Math.sqrt(), System.out.println
Math - class
sqrt - static method
print/println - instance method
But Not able to identify static methods of nested classes.
package so;
class Outer {
static String outerVar = "ABC";
class InsInner {
static void show() {
System.out.println("Instance inner "+outerVar);
}
}
static class StaticInner {
static void show() {
System.out.println("Static inner class static method "+outerVar);
}
}
}
public class NestedClass {
public static void main(String[] args) {
Outer.InsInner.show();
Outer.StaticInner.show();
}
}
Why both static and non static classes have same convention?
Outer.InsInner.show();
Outer.StaticInner.show();
答案1
得分: 1
因为show()
在这两个地方都是static
。当一个方法是static
时,它不需要实例来操作,所以你不需要一个InsInner
或StaticInner
来调用show()
,调用看起来是一样的。如果你把show()
变成实例方法,那么它就会有所不同。像这样,
class Outer {
static String outerVar = "ABC";
class InsInner {
void show() {
System.out.println("Instance inner " + outerVar);
}
}
static class StaticInner {
void show() {
System.out.println("Static inner class static method " + outerVar);
}
}
public static void main(String[] args) {
new Outer().new InsInner().show();
new Outer.StaticInner().show();
}
}
英文:
Because show()
is static
in both places. When a method is static
it does not require an instance to operate, so you don't need an InsInner
or StaticInner
to call either show()
and the calls look the same. If you make show()
an instance method, then it would have to differ. Like,
class Outer {
static String outerVar = "ABC";
class InsInner {
void show() {
System.out.println("Instance inner " + outerVar);
}
}
static class StaticInner {
void show() {
System.out.println("Static inner class static method " + outerVar);
}
}
public static void main(String[] args) {
new Outer().new InsInner().show();
new Outer.StaticInner().show();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论