我是一名java初學者,我正在學習使用接口。據我所知,實現接口的類必須給出抽象方法的定義,如果它是一個具體的類。但我做了下面的步驟,錯誤地得到了一個非常不尋常的行爲。以下是我所做的。抽象方法的不尋常行爲
首先,我創建了一個名爲可打印的接口,並在文件中保存Printable.java它:
public interface Printable{
public void print();
public void show();
default void defaultMethod(){
System.out.println("default method is called");
}
}
然後我創建了兩個類ClassA和ClassB的實現打印如下:
ClassA的:
public class ClassA implements Printable{
public ClassA(){
System.out.println("object of class A is created");
}
public void print(){
System.out.println("print called from class A");
}
}
B類:
public class ClassB implements Printable{
public ClassB(){
System.out.println("Object of class B is created");
}
public void print(){
System.out.println("print called from class B");
}
}
我創建了一個名爲Test的測試類,如下所示:
public class Test{
public static void main(String args[]){
ClassA a1 = new ClassA();
a1.print();
ClassB b1 = new ClassB();
b1.print();
a1.defaultMethod();
}
}
我知道在編譯)接口可打印的上面的類我會得到錯誤,因爲我故意沒給的抽象方法秀定義(在類新A和B,我編譯類,如下所示:
[email protected]:~/java/upload$ ls
ClassA.java ClassB.java Printable.java Test.java
[email protected]:~/java/upload$ javac Test.java
./ClassA.java:1: error: ClassA is not abstract and does not override abstract method show() in Printable
public class ClassA implements Printable{
^
./ClassB.java:1: error: ClassB is not abstract and does not override abstract method show() in Printable
public class ClassB implements Printable{
^
2 errors
[email protected]:~/java/upload$
所以我想在打印發表評論的方法顯示()的聲明,我這樣做,並保存文件如下:
public interface Printable{
public void print();
//public void show();
default void defaultMethod(){
System.out.println("default method is called");
}
}
和現在重新編譯的錯誤都不見了,輸出率爲:
[email protected]:~/java/upload$ javac Test.java
[email protected]:~/java/upload$ ls
ClassA.class ClassA.java ClassB.class ClassB.java Printable.class Printable.java Test.class Test.java
[email protected]:~/java/upload$ java Test
object of class A is created
print called from class A
Object of class B is created
print called from class B
default method is called
[email protected]:~/java/upload$
這是一切ok到此級別,但現在我決定取消演出()的聲明中打印的註釋,保存它如下:
public interface Printable{
public void print();
public void show();
default void defaultMethod(){
System.out.println("default method is called");
}
}
現在我重新編譯它,並希望再次得到錯誤,但這次重新編譯的javac沒有給任何錯誤,但它應該得到的,因爲不給執行的方法顯示錯誤() 。它編譯全成如下:
[email protected]:~/java/upload$ ls
ClassA.class ClassA.java ClassB.class ClassB.java Printable.class Printable.java Test.class Test.java
[email protected]:~/java/upload$ javac Test.java
[email protected]:~/java/upload$ java Test
object of class A is created
print called from class A
Object of class B is created
print called from class B
default method is called
[email protected]:~/java/upload$
我無法理解爲什麼編譯器沒有再次給了錯誤,我沒有任何改變我做了後保存每個文件。請幫忙,並抱歉有任何錯誤。
在你運行之前重新編譯所有的類,我建議你開始使用編輯器,這樣你就不會在不知不覺中犯這些錯誤。 – karthikdivi
你真的需要學習如何使用像'Maven'或'Gradle'這樣的構建系統。 –