zoukankan      html  css  js  c++  java
  • Static Fields and Methods

    If you define a field as static, then there is only one such field per class. In contrast, each object has its own copy of all instance fields. For example:

    class Employee
    {
        private static int nextID = 1;
    
        private int id;
        ...
    }
    
    public void setId()
    {
        id = nextId;
        nextId++;
    }
    

    Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression Math.pow(x,a) computes the power. It does not user any Math object to carry out its task. In other words, **it has no implicit parameter*. You can think of static methods as methods that don't have a this parameter.

    A static method of the Employee class cannot access the id instance field because it does not operate on an object. However, a static method can access a static field. For example:

    public static int getNextId()
    {
        return nextId; //returns static field
    }
    

    To call this method, you supply the name of the class:

    int n = Employee.getNextid();
    

    You would need to have an object reference of type Employee to invoke the method if you omit the keyword static.

  • 相关阅读:
    年入50万的众生相
    【史上最全面经】银行类
    Dubbo背景和简介
    剑指Offer66题的总结、目录
    如何写一份更好的简历
    Linux命令 file
    Linux命令 umask
    Linux perm
    Linux 命令 which whereis locate find
    Linux命令 diff cmp patch
  • 原文地址:https://www.cnblogs.com/yaos/p/14014303.html
Copyright © 2011-2022 走看看