java介面中定義的常量的存取方法

來源:互聯網
上載者:User

  我們在定義常量的時候,可以把常量定義在介面裡面,如:

packageorg.zy.demo.base;

publicinterfaceInterfaceDemo{

finalStringname="thisismyname";

}

  上面是我定義的介面和常量。

  常量的定義沒有指明publicstatic

  我實現此介面:

packageorg.zy.demo.base;

publicclassInterfaceImplimplementsInterfaceDemo{

}

  那麼我們如何訪問呢?

  我做了一個demo:

packageorg.zy.demo.base;

publicclassMainDemo{

publicstaticvoidmain(String[]args){

InterfaceImplii=newInterfaceImpl();

Stringname=InterfaceDemo.name;

System.out.println(name);

Stringn=ii.name;

System.out.println(n);

}

}

  執行的結果如下:

  thisismyname

  thisismyname

  在上面的程式中,我們使用了兩種不同的方法來取得了name的值。

  由第一種方法我們可以知道:

  其實介面內定義的所有的屬性和方法都是public類型的。如果是屬性,其預設是

  Publicstatic的

  通過第二種方法我們可以知道,此屬性是公有的。否則我們怎麼能直接存取呢?

  由上面的結論我們可以知道為什麼我們定義介面中的方法的時候,不用添加public,如泥可以定義如下方法:

PublicInterfaceA{

A();

}

  當然你也可以:

PublicInterfaceA{

PublicA();

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.