[英]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.