What’s the difference between an interface and an abstract class in Java?

原文

What’s the difference between an interface and an abstract class in Java?

It’s best to start answering this question with a brief definition of abstract classes and interfaces and then explore the differences between the two.

A class must be declared abstract when it has one or more abstract methods. A method is declared abstract when it has a method heading, but no body – which means that an abstract method has no implementation code inside curly braces like normal methods do.

When to use abstract methods in Java?

Why you would want to declare a method as abstract is best illustrated by an example. Take a look at the code below:

/* the Figure class must be declared as abstract
   because it contains an abstract method  */

public abstract class Figure
{
    /* because this is an abstract method the
       body will be blank  */
    public abstract float getArea();
}

public class Circle extends Figure
{
    private float radius;

    public float getArea()
    {
        return (3.14 * (radius ^ 2));
    }
}

public class Rectangle extends Figure
{
    private float length, width;

    public float getArea(Figure other)
    {
        return length * width;
    }
}

Why did we declare the getArea method to be abstract in the Figure class? Well, what does the getArea method do? It returns the area of a specific shape. But, because the Figure class isn’t a specificshape (like a Circle or a Rectangle), there’s really no definition we can give the getArea method inside the Figure class. That’s why we declare the method and the Figure class to be abstract. Any classes that derive from the Figure class basically has 2 options: 1. The derived class must provide a definition for the getArea method OR 2. The derived class must be declared abstract itself.

A non abstract class is called a concrete class

You should also know that any non abstract class is called a concrete class. Knowing your terminology defintely pays off in an interview.

Now that we’ve explored the abstract method/class concepts, let’s get into the concept of interfaces and how they differ from abstract classes.

Java interface versus abstract class

An interface differs from an abstract class because an interface is not a class. An interface is essentially a type that can be satisfied by any class that implements the interface.

Any class that implements an interface must satisfy 2 conditions:

  • It must have the phrase "implements Interface_Name" at the beginning of the class definiton.
  • It must implement all of the method headings listed in the interface definition.

Abstract classes and inheritance

With an interface on the other hand, the relationship between the interface itself and the class implementing the interface is not necessarily strong. For example, if we have a class called "House", that class could also implement an interface called "AirConditioning". Having air conditioning not really an essential part of a House (although some may argue that point), and the relationship is not as strong as, say, the relationship between a “TownHouse” class and the "House" class or the relationship between an “Apartment” class that derives from a “House” class.1. Abstract classes are meant to be inherited from, and when one class inherits from another it means that there is a strong relationship between the 2 classes. For instance, if we have an abstract base class called "Canine", any deriving class should be an animal that belongs to the Canine family (like a Dog or a Wolf). The reason we use the word "should" is because it is up to the Java developer to ensure that relationship is maintained.

Because a TownHouse is a type of House, that relationship is very strong, and would be more appropriately defined through inheritance instead of interfaces.

So, we can summarize this first point by saying that an abstract class would be more appropriate when there is a strong relationship between the abstract class and the classes that will derive from it. Again, this is because an abstract class is very closely linked to inheritance, which implies a strong relationship. But, with interfaces there need not be a strong relationship between the interface and the classes that implement the interface.

Interfaces are a good substitute for multiple inheritance

2. Java does not allow multiple inheritance – see the discussion onJava Multiple Inheritance if you need a refresher on this. In Java, a class can only derive from one class, whether it’s abstract or not. However, a class can implement multiple interfaces – which could be considered as an alternative to for multiple inheritance. So, one major difference is that a Java class can inherit from only one abstract class, but can implement multiple interfaces.

Abstract classes can have some implementation code

3. An abstract class may provide some methods with definitions – so an abstract class can have non-abstract methods with actual implementation details. An abstract class can also have constructors and instance variables as well. An interface, however, can not provide any method definitions – it can only provide method headings. Any class that implements the interface is responsible for providing the method definition/implementation.

When to use abstract class and interface in Java

Here are some guidelines on when to use an abstract class and when to use interfaces in Java:

    • An abstract class is good if you think you will plan on using inheritance since it provides a common base class implementation to derived classes.
    • An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must be public.
    • If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface, then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle.
    • Interfaces are a good choice when you think that the API will not change for a while.
    • Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces.

补充:

1. Variables in interface must be public, static, final

时间: 2024-10-21 06:44:35

What’s the difference between an interface and an abstract class in Java?的相关文章

接口Interface和抽象类abstract class的区别

abstract class和interface是Java语言中对于抽象类定义进行支持的两种机制,正是由于这两种机制的存在,才赋予了Java强大的面向对象能力. abstract class和interface之间在对于抽象类定义的支持方面具有很大的相似性,甚至可以相互替换,因此很多开发者在进行抽象类定义时对于 abstract class和interface的选择显得比较随意. 其实,两者之间还是有很大的区别的,对于它们的选择甚至反映出对于问题领域本质的理解.对于设计意图的理解是否正确.合理.

PHP接口(interface)和抽象类(abstract)

interface 定义了一个接口类,它里面的方法其子类必须实现.接口是类的一个模板,其子类必须实现接口中定义的所有方法. interface User{ function getHeight($height); function getWeight($weight); } class my implements User{ function getHeight($username){ echo $height; } function getWeight($weight){ echo $weig

接口 interface ,抽象类 abstract

接口是类的模板,类是对象的模板. 使用关键字interface 定义了一个接口Person,接口中有两个方法: 使用关键字implements实现了接口,实现类Man里需要实现接口中的所有方法,否则会报错. L类中的factory方法是调用接口的一个例子,其中传入的参数$user 使用了 Person 接口进行了类型限制,说明传入的参数必须是实现了Person接口的类(比如说Man类). 接口可以被多次实现,比如把代码中的Man类复制粘贴改成Woman类,就是另外一次实现接口了. 接口也是可以被

C++虚函数virtual,纯虚函数pure virtual和Java抽象函数abstract,接口interface与抽象类abstract class的比较

由于C++和Java都是面向对象的编程语言,它们的多态性就分别靠虚函数和抽象函数来实现. C++的虚函数可以在子类中重写,调用是根据实际的对象来判别的,而不是通过指针类型(普通函数的调用是根据当前指针类型来判断的).纯虚函数是一种在父函数中只定义而不实现的一种函数,不能用来声明对象,也可以被称为抽象类.纯虚函数的实现也可以在类声明外进行定义.C++中的抽象类abstract class是指至少有一个纯虚函数的类,如果一个类全部由纯虚函数组成,不包括任何的实现,被称为纯虚类. Java中的普通函数

The Interface and Class Hierarchy Diagram of Java Collections

原文链接:http://www.programcreek.com/2009/02/the-interface-and-class-hierarchy-for-collections/   1. Collection vs Collections First of all, "Collection" and "Collections" are two different concepts. As you will see from the hierarchy diag

java abstract与interface解析

java abstract与interface解析 abstract 定义 在面向对象的概念中,所有的对象都是通过类来描述.但是,反过来,不是所有的类都是用来描述对象的(把类具体化).如果一个类没有包含足够的信息来描述一个具体的对象,那么这个类就是抽象类. 比如,我们进行一个图形编辑软件的开发,就会发现问题域中存在圆,三角形这样一些具体的概念,它们是不同的,但是它们又都属于形状这样一个概念.形状这个概念在问题域中是不存在的,它就是一个抽象的概念.正是因为抽象的概念在问题领域没有对应的具体概念,所

JI_5

Part I. The CV Review Pass the CV to THREE developers Each dev should mark YES/NO on the CV Reject any CVs with TWO No's Part II. The Phone Interview 1. What *EXACTLY* did you code last? Have them explain in detail.. Then discuss within that context…

线程池的应用及Callable接口的使用

Java代码   public interface Executor { /** * Executes the given command at some time in the future.  The command * may execute in a new thread, in a pooled thread, or in the calling * thread, at the discretion of the <tt>Executor</tt> implementa

NIO-Channel接口分析

目录 NIO-Channel源码分析 目录 前言 接口 SCTP协议 UDP协议 TCP协议 文件 总结 相关文献 NIO-Channel源码分析 目录 NIO-概览 NIO-Buffer NIO-Channel NIO-Channel源码分析 前言 本来是想学习Netty的,但是Netty是一个NIO框架,因此在学习netty之前,还是先梳理一下NIO的知识.通过剖析源码理解NIO的设计原理. 本系列文章针对的是JDK1.8.0.161的源码. 上一篇介绍了Channel的基本使用,下面对Ch