zoukankan      html  css  js  c++  java
  • Static关键字

    ## 关于static关键字的用法

    ```
    /*
    一旦用了static关键字,这样的内容不在属于对象自己,而是属于类的
    并且可以直接使用类名称进行调用,若没有只能先创建对象,然后通过对象调用
     */
    ```

    **先定义一个类**

    包含有static关键字修饰的成员变量和成员方法以及没有用static 关键字修饰的成员变量和成员方法比较他们有什么不同;

    ```java
    //Animal类仅定义一些成员变量和成员方法
    public class Animal {
        String  variety ;
        static int old ;
        boolean  three;
        public  void  heavior (){

            System.out.println("觅食、繁衍、休息");

        }

        public static void nomdie(int a){
            if(a==0) {System.out.println("落叶归根");}
        }
    }
    ```

    创建另一个类来调用 上述类的成员变量和成员方法,寻找static关键字的特点:

    ```java
    public class Static00 {
        public static void main(String[] args){
            Animal dog = new Animal();
            dog.three = true;
            dog.variety = "犬科";
            dog.old = 7;

            Animal  cat = new Animal();
            System.out.println(dog.three+","+dog.variety+","+dog.old);//true , 犬科, 7
            System.out.println(cat.three+","+cat.variety+","+cat.old);//false,null(默认) 7
            //凡是本类的数据都共享同一份数据
            System.out.println(Animal.old);//7
            //直接用类名调用成员变量

            Animal.nomdie(0);
            dog.nomdie(2);
           // Animal.heavior;  非static成员方法,不能通过类调用
            dog.heavior();
        }

    }
    ```

    static关键字声明以后,数据为同一类共享,可通过类直接调用。

  • 相关阅读:
    Maven关于web.xml中Servlet和Servlet映射的问题
    intellij idea的Maven项目运行报程序包找不到的错误
    修改Maven项目默认JDK版本
    刷题15. 3Sum
    刷题11. Container With Most Water
    刷题10. Regular Expression Matching
    刷题5. Longest Palindromic Substring
    刷题4. Median of Two Sorted Arrays
    刷题3. Longest Substring Without Repeating Characters
    刷题2. Add Two Numbers
  • 原文地址:https://www.cnblogs.com/susexuexi011/p/13756168.html
Copyright © 2011-2022 走看看