zoukankan      html  css  js  c++  java
  • 静态方法和非静态方法的区别

     首先,两者本质上的区别是:静态方法是在类中使用staitc修饰的方法,在类定义的时候已经被装载和分配。而非静态方法是不加static关键字的方法,在类定义时没有占用内存,只有在类被实例化成对象时,对象调用该方法才被分配内存。
     
           其次,静态方法中只能调用静态成员或者方法,不能调用非静态方法或者非静态成员,而非静态方法既可以调用静态成员或者方法又可以调用其他的非静态成员或者方法。
     
    例子1:静态方法的Main方法访问类中的非静态成员方法。
     
    class Test{
    public int sum(int a,int b){//非静态方法
    return a+b;
    }
    public static void main(String[] args){
    int result=sum(1,2);//静态方法调用非静态方法
    System.out.println("result="+result);
    }
    }
    结论:以上程序在编译时,会提示静态方法不能引用非静态方法的错误信息。(如下图所示)
     
     
     
     
     
    解决方法:
     
    一、静态方法只能访问静态方法和静态成员。
     
    class Test{
    public static int sum(int a,int b){//加入static关键字,变成静态方法
    return a+b;
    }
    public static void main(String[] args){
    int result=sum(1,2);//静态方法调用静态方法
    System.out.println("result="+result);
    }
    }
    二、非静态方法要被实例化才能被静态方法调用。
     
    class Test{
    public int sum(int a,int b){
    return a+b;
    }
    public static void main(String[] args){
    Test test=new Test();//实例化类
    int result=test.sum(1,2);//调用非静态方法
    System.out.println("result="+result);
    }
    }
  • 相关阅读:
    有了bootstrap,为什么还要做amaze ui
    互联网科普知识【野狗】
    诶,很有意思的点子——云适配
    nodeJS一些事儿
    主流浏览器js 引擎内核市场份额attialx总结vOa9
    50 个 Bootstrap 插件
    Bean Validation
    Spring Security的核心拦截器
    关于未来十年企业架构的十个关键词
    写一个函数对字符串数组排序,使所有变位词都相邻
  • 原文地址:https://www.cnblogs.com/xiewenyu/p/11495123.html
Copyright © 2011-2022 走看看