java 筆記(6) static關鍵字

來源:互聯網
上載者:User

標籤:name   this   上海   stat   under   屬性   北京   tco   system   

static關鍵字:

package com.dingding.staticdemo;class Person{    String name;    private static String country = "北京";    public Person(String name){        this.name = name;    }            public static String getCountry() {        return country;    }    public static void setCountry(String country) {        Person.country = country;    }    public void tell(){        System.out.println("姓名:"+name+" 出生地:"+country);    }}public class StaticDemo01 {    public static void main(String[] args) {        Person.setCountry("上海");//類方法(static)一般用於所用的執行個體對象都一樣的值的情況        Person p1 = new Person("張三");        p1.tell();                Person p2 = new Person("李四");        p2.tell();                Person p3 = new Person("王五");        p3.tell();    }}

 

運行結果:

姓名:張三 出生地:上海
姓名:李四 出生地:上海
姓名:王五 出生地:上海

 

分析:

1、類方法、類變數(static)一般用於所用的執行個體對象都是一樣的值的情況。

2、在main()方法中,代碼Person.setCountry("上海");是聲明靜態,所以它要在執行個體化前進行調用。

3、類變數的特點:所有對象和類共同擁有這個屬性。

java 筆記(6) static關鍵字

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.