• java 之 实例方法和类方法


    类方法:使用static修饰(静态方法),属于整个类的,不是属于某个实例的,只能处理static域或调用static方法;
    实例方法:属于对象的方法,由对象来调用。

    判断类方法,类方法的前面有static 修饰 

    public class Example { 
    
    float a, b; 
    
    // 这个是实例方法  
    void sum(float x, float y) { 
    a = max(x, y); 
    b = min(x, y); 
    } 
    

      

    // 类方法 
    static float getMax(float x, float y) { 
    float c; 
    c = max(x, y) * max(x, y); 
    return c; 
    } 
    

      

    // 类方法 
    static float max(float x, float y) { 
    return x <= y ? y : x; 
    } 
    
    // 实例方法 
    float min(float x, float y) { 
    return x <= y ? x : y; 
    } 
    }
    

      

    一个类中的方法可以互相调用。但要注意:实例方法可以调用该类中的其他方法,例如,sum()可以调用max()和min()。类方法只能调用其他类方法,不能调用实例方法。例如,getMaxSqrt()只能调用max()而不能调用min()。

    当类文件加载到内存时,实例方法不会被分配内存空间,只有在对象创建之后才会分配。而类方法在该类被加载到内存时就分配了相应的内存空间。

    实例方法既能对类变量操作也能对实例变量操作。

    类方法只能访问其他static方法。

    类方法只能访问其他static数据,类变量。


    欢迎交流学习,共同进步
    限本人水平有限,如有错误请指教,谢谢
  • 相关阅读:
    Python中 sys.argv[]的用法简明解释
    python多线程
    python 多进程
    shell----bash
    linux crontab
    Elastic search 概述
    Elastic search 入门
    Elastic search CURL命令
    Elastic search 基本使用
    Elastic search 字段折叠 collaose
  • 原文地址:https://www.cnblogs.com/__tudou__/p/5295547.html
Copyright © 2020-2023  润新知