Java语言支持在一个类中定义静态内部类,即嵌套类(nested class)。当一个类被封闭在一个外部类中时,这个被封闭的类被称为内部类,而封闭它的外部类则被称为外部类。值得注意的是,顶级类不能用static修饰,但内部类可以使用static进行修饰。接下来,我们来深入探讨静态内部类和非静态内部类之间的主...
System.out.println("Message from nested static class: " + msg); } } // 非静态内部类 public class InnerClass{ // 不管是静态方法还是非静态方法都可以在非静态内部类中访问 public void display(){ System.out.println("Message from non-static nested class: "+ msg); } } } class Main { //...
Inner i = o.new Inner(); 静态内部类使用场景一般是当外部类需要使用内部类,而内部类无需外部类资源,并且内部类可以单独创建的时候会考虑采用静态内部类的设计,在知道如何初始化静态内部类,在《Effective Java》第二章所描述的静态内部类builder阐述了如何使用静态内部类: public class Outer { private String nam...
内部类主要分为一下几类:1.静态内部类2.成员内部类2.局部内部类3.匿名内部类另外,内部类是编译期相关的,内部类会编译成一个单独的带有$符的.class文件。在程序的运行期Java虚拟机并不知道此类是内部类。静态内部类(1):静态内部类等同于外部类的静态属性,可以使用类名.的方式进行访问,可以...
publicclassTestMain { publicstaticvoidmain(String[] args) { //TODOAuto-generated method stub // new MainInStaticClass().print(); MainInStaticClass.Main.main(); newMainInStaticClass.Main(); } } 二、静态内部类的使用限制。 将某个内部类定义为静态类,跟将其他类定义为静态类的方法基本相同,引用...
Java Static Nested Classes vs. Non-static or Inner ClassesSometimes the two terminologies static nested class, and non-static or inner class create confusion and the difference becomes obscure. First of all a class defined within another class is necessarily a nested class. Nested classes come in...
报错:Non-static method 'xxx()' cannot be referenced from a static context 形如: 代码语言:javascript 代码运行次数:0 publicclassMyClass{publicvoidnonStaticMethod(){// 非静态方法实现}publicstaticvoidstaticMethod(){// 在静态方法中引用非静态方法,会导致错误nonStaticMethod();// 错误:Non-static method...
java 中静态方法与非静态方法的访问 public class StaticMethod { //定义一个非静态方法 public void callMe2() { System.out.println("This is a nonstatic method"); } //定义一个静态方法 public static void callMe() //静态方法 { System.out.println("This is a static method"); ...
1. public class TestStaticClass { 2. public static void main(String[] args) { 3. // 不需要new一个OutClass 4. new OuterClass.InnerClass(); 5. } 6. } 如果没有用static修饰InterClass,则只能按如下方式调用: Java代码 1. package inner_class; ...
Java is a Object Oriented Programming(OOP) language, which is often interpreted that we need objects to access methods and variables of a class, however this is not always true. While discussing static keyword in java, we learned that static members are