[英]Error extending from an abstract class and implementing the Comparable interface
[英]what is the difference between implementing from an interface and extending from the object class?
我是java新手,我希望這個問題不是太基本。 我無法理解為什么需要接口,以及實現和繼承之間的區別。
如果我想在我的程序中使用 Comparable 方法, (java.lang.Comparable)
為什么我不能讓我的類從Comparable
繼承?
public class Main {
public static void main(String[] args) {
class DocumentReader extends Comparable;
為什么 IntelliJ 說“這里沒有預期的接口”?
粗略地說,自 JDK 8 以來並不完全准確......但可以掌握基礎知識。
接口是實現接口的類必須具有的方法規范。 該接口不提供實現。 因此,說您的類“實現 Comparable”意味着它有義務提供具有特定簽名的 compareTo 方法。
一個類可能包含實際的方法實現,也可能包含成員數據。 擴展一個類本質上是該類的特化。 您可以獲得基類所做的一切,您可以修改(通過覆蓋基方法)或擴充(通過添加新方法)。
除了有抽象方法之類的東西,其中基類不提供實現,因此強制擴展類提供實現。
那么,從一個角度來看,您可以將接口視為一個抽象類,其中所有方法都是抽象的。 這是可行的,除了 Java 只允許一個類擴展一個類(沒有 'class X extends A, B'),但一個類可以實現多個接口('class X 實現 A, B' - 我的語法可能不准確)。 限制從多個類繼承是有技術原因的,但我會在這里跳過。
正如我在開始時所說的,這在 JDK 8 中並不完全正確——接口中有“默認方法”,所以這條線有點模糊。
我認為接口就像一個對象必須提供的插頭和插座類型的規范,如果它以標准方式連接到其他對象。 您希望對您的對象進行“比較”,以便其他組件可以按順序排列它們? 然后你必須實現 Comparable。
我試圖以編程方式解釋。 Extends :當你想擴展一個要在繼承中擴展的子類時,我們使用Java extends。 實現:當實現接口時,我們使用關鍵字實現。
擴展與實現:簡而言之,擴展用於擴展類,實現用於實現接口。
由於 Java 不支持多重繼承,這個問題可以通過多個接口克服。
擴展:
class Person
{
String name;
Person(String n)
{
name = "Person: " + n;
}
}
class Mother extends Person
{
Mother(String n)
{
super(n);
name = "Mother: " + n;
}
void FeedChildren()
{
System.out.println(name + " is feeding the kids ...");
}
}
class Wife extends Person
{
Wife(String n)
{
super(n);
name = "Wife: " + n;
}
void CallHusband()
{
System.out.println(name + " is calling the husband ...");
}
}
public class Test
{
public static void main(String args[])
{
Person p = new Person("Prerna");
Mother m = new Mother("Mahima");
Wife w = new Wife("Raani");
System.out.println("p is a " + p.name);
System.out.println("m is a " + m.name);
System.out.println("w is a " + w.name);
m.FeedChildren();
w.CallHusband();
}
}
這里的基類是 Person、Mother 和 Wife,但是當 Wife 和 Mother 是同一個人時,這就是我們正在談論的人。
工具
class Person
{
String name;
Person(String n)
{
name = "Person: " + n;
}
}
interface Mother
{
public void FeedChildren();
}
interface Wife
{
public void CallHusband();
}
class WifeAndMother extends Person implements Wife, Mother
{
WifeAndMother(String n)
{
super(n);
name = "Wife and mother: " + n;
}
public void FeedChildren()
{
System.out.println(name + " is feeding the children.");
}
public void CallHusband()
{
System.out.println(name + " is calling her husband.");
}
}
public class Test
{
public static void main(String args[])
{
Person p = new Person("Prerna");
WifeAndMother w = new WifeAndMother("Raani");
System.out.println("p is a " + p.name);
System.out.println("w is a " + w.name);
w.FeedChildren();
w.CallHusband();
}
}
您只能從一個類擴展並實現多個接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.