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