JAVA 重載,重寫(覆蓋)個人理解

來源:互聯網
上載者:User

標籤:java基礎

  1. 重載,一個java類裡有多個同名的方法,但參數列表不同,見下面代碼:


public class Caller {    /**     * 喊叫     *      * @param callMan     *            呼喊者     * @param callContent     *            呼喊內容     */    public void call(String callMan, String callContent) {        System.out.println("I am " + callMan + ", I will call " + callContent);    }    /**     * 喊叫     *      * @param callContent     *            呼喊內容     */    public void call(String callContent) {        System.out.println("I am hellokitty, I will call " + callContent);    }}



2. 重寫和覆蓋是一個概念,子類和父類有同名的方法名,且參數列表完全一致,在運行中子類的方法完全覆蓋父類方法.


使用情境,系統要支援多種緩衝機制,memcache,ehcache各實現一套方法


(1)定義介面 CacheService

public interface CacheService {    /**     * 緩衝     *      * @param cacheKey     *            緩衝key     * @param cacheContent     *            待緩衝內容     */    public void cache(String cacheKey, Object cacheContent);}


(2) EhcacheCacheImpl實現:

public class EhcacheCacheServiceImpl implements CacheService {    @Override    public void cache(String cacheKey, Object cacheContent) {        System.out.println("Cached by ehcache!");    }}


(3) MemcacheServiceImpl實現:

public class MemcacheServiceImpl implements CacheService {    @Override    public void cache(String cacheKey, Object cacheContent) {        System.out.println("Cached by memcache!");    }}


(4)測試

public class CacheTest {    public static void main(String[] args) {        CacheService cacheService1 = new EhcacheCacheServiceImpl();        cacheService1.cache("", "");        CacheService cacheService2 = new MemcacheServiceImpl();        cacheService2.cache("", "");    }}執行結果:Cached by ehcache!Cached by memcache!


(5)如果結合Springs使用,可以通過修改設定檔的方式,靈活修改實現。

import org.springframework.beans.factory.annotation.Autowired;public class CacheTest1 {    @Autowired    private CacheService cacheService;    private void cache(String cacheKey, Object cacheContent) {        cacheService.cache(cacheKey, cacheContent);    }    public static void main(String[] args) {        CacheTest1 newCacheTest = new CacheTest1();        newCacheTest.cache("", "");    }}



本文出自 “12314480” 部落格,請務必保留此出處http://12324480.blog.51cto.com/12314480/1875421

JAVA 重載,重寫(覆蓋)個人理解

聯繫我們

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