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.

  • 相关阅读:
    C# 根据二级栏目Id查询出所属文章的信息列表
    C#网站首页制作MVC
    C#Mvc退出登录
    C#Mvc修改密码
    C#网站开发之内容页Content
    C#Mvc登录功能
    Linux命令——shell
    学习笔记cisco常用命令
    性能相关术语
    Linux命令(一)
  • 原文地址:https://www.cnblogs.com/yaos/p/14014303.html
Copyright © 2011-2022 走看看