繁体   English   中英

java接口方法返回值本身

[英]java interface method return value is itself

我是Java的初学者。 我想在其中创建新的追加字符串方法

MyBuffer buf = new MyBuffer(1); buf.append("This");

会将字符串“ This”添加到buf中,但是

MyBuffer buf = new MyBuffer(1); buf.append("This"); buf.append("That");

将显示空间不足的错误。

我有2个Java类和2个Java接口,如下所示:

public interface MyAppendable {
public abstract MyAppendable append(String word);
}

public interface MyFlushable {
public abstract void flush();
}

public class MyBuffer implements MyFlushable, MyAppendable {
String buffer = "";
int initialSize;
int bufferSize;
public MyBuffer(int initialSize) {
    this.initialSize = initialSize;
    this.bufferSize = initialSize;
}
public MyAppendable append(String word) {
    MyAppendable myappendable = new MyBuffer(bufferSize - 1);
    if(bufferSize > 0) {
        buffer = buffer + word;
        bufferSize--;
    } else {
        System.out.println("oops, not enough space, cannot add " + word + "into buffer");
    }
    return myappendable;
}

public void flush() {
    buffer = "";
    bufferSize = initialSize;
}

public String toString() {
    return buffer;
}

}

public class MyBufferDemo {
public static void main(String[] str) {
    MyBuffer buf = new MyBuffer(5);
    buf.append("This");
    buf.append(" ");
    buf.append("is");
    buf.append(" ");
    buf.append("MyBufferDemo");
    System.out.println(buf.toString());
    buf.flush();
    buf.append("A").append("B").append("C");
    System.out.println(buf.toString());
    buf.append("D").append("E").append("F");
    System.out.println(buf.toString());
}
}

但是代替

This is MyBufferDemo
ABC
oops, not enough space, cannot add F into buffer
ABCDE

输出是

This is MyBufferDemo
A
AD

实际上,我对方法附加中的返回值是其自己的接口感到困惑。 有可能这样做吗? 谢谢。

首先,在此代码中,您是否真的需要此接口来完成您正在寻找的工作? 我不这么认为。 但是,您需要像在buf.append(“Hello”)之前的行中一样添加字符,这才可以工作。

您不能使用myAppendable接口来调用方法append,它没有显式声明,仅是一个接口。

除此以外,我建议您不要在同一代码中使用接口和抽象方法。 它们之间有一些区别。

只需检查要添加的字符串是否适合,然后再添加它并从缓冲区中减去单词的总长度即可。 目前,您要从缓冲区中减去1,但是如果单词的长度为5个字符,那么您希望从缓冲区中减去5,而不是像您当前所做的那样减去1,

public MyAppendable append(String word) {
    if(bufferSize - word.length() >= 0) {
        buffer = buffer + word;
        bufferSize -= word.length();
        //create your copy...
        MyAppendable myappendable = new MyBuffer(this.initialSize);//i believe this should be the size of the buffer and not the initial size variable
        myappendable.buffer = this.buffer;
        myappendable.initialSize = this.initialSize;
        myappendable.bufferSize = this.bufferSize;
        return myappendable;
    } else {
        System.out.println("oops, not enough space, cannot add " + word + "into buffer");
        return this;
    }
}

最后,您永远不会使用返回的对象,所以我不确定为什么要在append方法中返回一个对象。

暂无
暂无

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

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