可能重复:
Interface vs Base class
Interface vs Abstract Class (general OO)
Abstract class vs Interface in Java
所以我正在学习编程课程中的接口和抽象类。这两个主题看起来非常相似。我知道它们都与继承有关,但两者之间有什么区别?
答案 0 :(得分:1)
抽象类可能包含方法体中的代码,这在接口中是不允许的。
答案 1 :(得分:0)
接口具有必须由实现它的类定义的方法。
抽象类是类似的。但是,在抽象类中,它可以包含继承类将自动调用的方法定义。
底线:如果所有实现类对方法的定义完全不同,请使用接口。如果继承类共享某些定义并且对某些方法有不同的定义,请使用抽象类。
示例:
public interface Shape {
public float getArea();
public void doThings();
}
public class Circle implements Shape{
public float getArea() {
return Math.PI * R * R;
}
public void doThings() { }
}
public abstract class Quadilateral implements Shape {
public float getArea() { // defined
return l * h;
}
public abstract void doThings(); // left abstract for inheriting classes
}
public class Rectangle extends Quadilateral {
public void doThings() {
// does things
}
}
public class Parallelogram extends Quadilateral {
public void doThings() {
// does things
}
}
答案 2 :(得分:0)
抽象类可以有方法,而接口不能有它们。
我通常会这样想:
例如,您可能想要创建一个Animal
类。然后有一个Dog
和Cat
类。狗和猫都睡了。所以你希望他们都有睡眠方法。他们的睡眠方式基本相同。因此,您希望Animal
类保留该方法(因为Dog
和Cat
的方法相同。
public abstract class Animal {
public void sleep() {
//make ZZZZ appear in the air or whatever
}
}
public class Dog extends Animal {
//This class automatically has the sleep method
}
public class Cat extends Animal {
//This class automatically has the sleep method
}
另一方面,假设您有Snake
和Shark
课程。蛇和鲨鱼都会发作,但攻击方式不同(毒液与叮咬)。所以你可能有一个Attacker
界面。
public interface Attacker {
//We HAVE to have this here
public void attack(); //Note - we didn't write the method here, just declared
}
public Snake implements Attacker {
//We HAVE to have this here
public void attack() {
//inject venom
}
}
public Shark implements Attacker {
public void attack() {
//rip apart
}
}
请注意,抽象类也可以使用未定义的方法(如接口)。因此,您可以在public void makeMeanSound();
中拥有Animal
,然后获得Dog
咆哮和Cat
嘶嘶声。主要区别在于抽象类可以编写实际的方法。
接口 - 强制写入方法(即强制Snake
和Shark
使用attack()
方法。
抽象类 - 为子类提供常用方法。
答案 3 :(得分:0)
有两个主要区别。