简体   繁体   English

无法使用接口的getter方法

[英]Not able to use getter method of Interface

I have written below code, just to play with interface, Would you please tell where I have gone wrong here? 我已经编写了下面的代码,仅用于界面操作,请您告诉我我哪里出问题了?

This is my interface: 这是我的界面:

package com.home.intetest;

public interface IFoo {

    public abstract String doWork(String str) throws Exception;

}

This is where I have implemented, 这是我实施的地方

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;
    }

}

Now I am trying to call them from main, using getter method, its giving me error,in line where I am using getiFoo method 现在我正在尝试使用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 1个

The line 线

getiFoo().doWork(str);

can not be called, you need a instance of TestMail first! 不能被调用,首先需要一个TestMail实例! So boot-up your Application like this: 因此,像这样启动您的应用程序:

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

2 2

The error you recieve is a NullPointerException now because iFoo is always null . 您现在收到的错误是NullPointerException因为iFoo始终为null

Create a instance in the getter using the default constructor like this: 使用默认构造函数在getter中创建一个实例,如下所示:

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

Or inside the declaration like this: 或在这样的声明中:

private IFoo iFoo = new FooImpl(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM