2013-09-21 81 views
1

我正在閱讀使用Java的面向對象的數據結構,我在第2章。我決定嘗試一下他們在那裏的練習,但代碼似乎對我甚至沒有作用盡管他們直接從書中來了。有人可以澄清這一點嗎?接口和StringLog混淆

package chapter2; 

public interface StringLogInterface 
{ 
    void insert(String element); 
    boolean isFull(); 
    int size(); 
    boolean contains(String element); 
    void clear(); 
    String getName(); 
    String toString(); 
} 

該項目使用三個文件,我發佈了其餘兩個下面。

package chapter2; 

public class ArrayStringLog 
{ 
    protected String name;    
    protected String[] log;    
    protected int lastIndex = -1;  

    public ArrayStringLog(String name, int maxSize) 
    { 
    log = new String[maxSize]; 
    this.name = name; 
    } 

    public ArrayStringLog(String name) 
    { 
    log = new String[100]; 
    this.name = name; 
    } 

    public void insert(String element) 
    {  
    lastIndex++; 
    log[lastIndex] = element; 
    } 

    public boolean isFull() 
    {    
    if (lastIndex == (log.length - 1)) 
     return true; 
    else 
     return false; 
    } 

    public int size() 
    { 
    return (lastIndex + 1); 
    } 

    public boolean contains(String element) 
    {     
    int location = 0; 
    while (location <= lastIndex) 
    { 
     if (element.equalsIgnoreCase(log[location])) // if they match 
     return true; 
     else 
     location++; 
    } 
    return false; 
    } 

    public void clear() 
    {     
    for (int i = 0; i <= lastIndex; i++) 
     log[i] = null; 
    lastIndex = -1; 
    } 

    public String getName() 
    { 
    return name; 
    } 

    public String toString() 
    { 
    String logString = "Log: " + name + "\n\n"; 

    for (int i = 0; i <= lastIndex; i++) 
     logString = logString + (i+1) + ". " + log[i] + "\n"; 

    return logString; 
    } 
} 

最後一部分:

package chapter2; 

public class UseStringLog 
{ 
    public static void main(String[] args) 
    { 
    StringLogInterface sample; 
    sample = new ArrayStringLog("Example Use"); 
    sample.insert("Elvis"); 
    sample.insert("King Louis XII"); 
    sample.insert("Captain Kirk"); 
    System.out.println(sample); 
    System.out.println("The size of the log is " + sample.size()); 
    System.out.println("Elvis is in the log: " + sample.contains("Elvis")); 
    System.out.println("Santa is in the log: " + sample.contains("Santa")); 
    } 
} 

這最後一部分是什麼讓我困惑。就行了,

sample = new ArrayStringLog("Example Use"); 

NetBeans的說:「無與倫比的類型,需要:StringLogInterface,發現:ArrayStringLog

他們都成功地建立,但是它不應該在最後打印三個println語句的最後一個文件?出來的東西

回答

2

ArrayStringLog實施StringLogInterface

public class ArrayStringLog implements StringLogInterface { 
    // ... 
} 

只有這樣,這是可能的:

StringLogInterface sample; 
sample = new ArrayStringLog("Example Use"); 
+0

擺脫了錯誤,但它仍然不會給我這三個println語句,當我運行它? – KTF