java 主类的main方法调用其他方法

方法1:A a=new test().new A(); 内部类对象通过外部类的实例对象调用其内部类构造方法产生,如下:

复制代码

 1 public class test{  
 2      class A{  
 3            void fA(){  
 4                System.out.println("we are students");  
 5               }  
 6         }  
 7      public static void main(String args[]){  
 8         System.out.println("Hello, 欢迎学习JAVA");  
 9         A a=new test().new A();  //使用内部类  
10         a.fA();     
11         }  
12 }   

复制代码

方法2: fA()方法设为静态方法。 当主类加载到内存,fA()分配了入口地址,如下:

复制代码

public class test{  
     static void fA(){  
         System.out.println("we are students");  
         }  
    public static void main(String args[]){  
        System.out.println("Hello, 欢迎学习JAVA");  
        fA(); //使用静态方法  
        }  
}   

复制代码

方法3: class A与 主类并列,如下:

public class test{  
    public static void main(String args[]){  
        System.out.println("Hello, 欢迎学习JAVA");  
        A a=new A();  //使用外部类  
        a.fA();     
        }  
}   
class A{  
      void fA(){  
         System.out.println("we are students");  
         }  
      }

猜你喜欢

转载自blog.csdn.net/u013323018/article/details/82831340