我从未在任何书籍或讲座中见过这种函数调用

时间:2018-09-22 16:44:52

标签: java

  

存在编译时错误   说“无效不能取消引用”   为什么我们这里需要具有返回类型的函数?

class Hello {
    public void greet() {
        System.out.print("Hello! ");
    }

    public void name() {
        System.out.print("Tanzeel");
    }

    public void how() {
        System.out.println("How are you?");
    }

    public void wish() {
        System.out.println("Have a nice day");
    }
}

class MainClass {
   public static void main(String[] args) {
       new Hello().greet().name().how().wish();
   }
}

3 个答案:

答案 0 :(得分:1)

要使代码正常工作,您应该返回Hello而不是void

class Hello {
    public Hello greet() {
        System.out.print("Hello! ");
        return this;
    }

    public Hello name() {
        System.out.print("Tanzeel");
        return this;
    }

    public Hello how() {
        System.out.println(". How are you?");
        return this;
    }

    public Hello wish() {
        System.out.println(". Have a nice day");
        return this;
    }
}

class MainClass {
   public static void main(String[] args) {
       new Hello().greet().name().how().wish();
   }
}

答案 1 :(得分:1)

因为new Hello()返回Hello的实例。当您致电greet()时,您会得到一个void,这就是问题开始的地方。

要继续使用此代码,您要么需要像这样拆分语句:

Hello hello = new Hello();
hello.greet();
hello.name();
// ...

...或将所有方法的返回类型更改为Hello,并在每个方法的末尾添加return this

答案 2 :(得分:1)

您无法在void上调用方法,因此编译错误。

这种链式调用方式是一种优雅的连续调用多个方法的方法,无需将它们分离为单独的语句,但是为了使其正常工作,这些方法中的每一个都需要返回一个Hello实例,例如同一个:

class Hello {
    public Hello greet() {
        System.out.print("Hello! ");
        return this;
    }

    public Hello name() {
        System.out.print("Tanzeel");
        return this;
    }

    public Hello how() {
        System.out.println(". How are you?");
        return this;
    }

    public Hello wish() {
        System.out.println(". Have a nice day");
        return this;
    }
}