簡體   English   中英

無法使用接口的getter方法

[英]Not able to use getter method of Interface

我已經編寫了下面的代碼,僅用於界面操作,請您告訴我我哪里出問題了?

這是我的界面:

package com.home.intetest;

public interface IFoo {

    public abstract String doWork(String str) throws Exception;

}

這是我實施的地方

package com.home.intetest;

public class FooImpl implements IFoo {

    @Override
    public String doWork(String str) throws Exception {

        if(str !=null) {
            System.out.println(str);
        }else{
            System.out.println("Wrongggg");
        }

        return str;
    }

}

現在我正在嘗試使用getter方法從main調用它們,這在我使用getiFoo方法的地方給了我錯誤

package com.home.intetest;


public class TestMain {

    private IFoo iFoo;

    public IFoo getiFoo() {
        return iFoo;
    }

    public void setiFoo(IFoo iFoo) {
        this.iFoo = iFoo;
    }


    public static void main(String[] args) {

        String str = "Work method";
        callWorkMethod(str);
    }

    private static void callWorkMethod(String str) {

        String s = getiFoo().doWork(str);

    }

}

1個

getiFoo().doWork(str);

不能被調用,首先需要一個TestMail實例! 因此,像這樣啟動您的應用程序:

new TestMain().getiFoo().doWork(str);

2

您現在收到的錯誤是NullPointerException因為iFoo始終為null

使用默認構造函數在getter中創建一個實例,如下所示:

public IFoo getiFoo() {
    if (iFoo == null) {
       iFoo = new FooImpl();
    }
    return iFoo;
}

或在這樣的聲明中:

private IFoo iFoo = new FooImpl(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM