原文

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

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

  1. 【转载】#445 - Differences Between an Interface and an Abstract Class

    An interface provides a list of members, without an implementation, that a class can choose to imple ...

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

    interface 定义了一个接口类,它里面的方法其子类必须实现.接口是类的一个模板,其子类必须实现接口中定义的所有方法. interface User{     function getHeight ...

  3. PHP的接口类(interface)和抽象类(abstract)的区别

    <?php /** * 接口类:interface * 其实他们的作用很简单,当有很多人一起开发一个项目时,可能都会去调用别人写的一些类, * 那你就会问,我怎么知道他的某个功能的实现方法是怎么 ...

  4. java的this static public protected private abstract interface 在python的对应,java python一些区别

    1.因为工作的原因,最近使用了三个多月的java作为主力语言.很早之前在菜鸟教程也看过java文档两遍,但实践少,处于能看懂写出来不流畅的状态(对于java必须要略懂,不能能看到就头疼跳过,因为现在百 ...

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

    由于C++和Java都是面向对象的编程语言,它们的多态性就分别靠虚函数和抽象函数来实现. C++的虚函数可以在子类中重写,调用是根据实际的对象来判别的,而不是通过指针类型(普通函数的调用是根据当前指针 ...

  6. Class Abstraction -- Object Interfaces

    <?php /* PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be in ...

  7. 115 Java Interview Questions and Answers – The ULTIMATE List--reference

    In this tutorial we will discuss about different types of questions that can be used in a Java inter ...

  8. Java 英文面试题

    1. Q: What is HashMap and Map?A: Map is Interface and Hashmap is class that implements that. 2. Q: D ...

  9. java 多线程学习

    一.概念 程序.进程.线程 程序   是计算机指令的集合. 进程   是一个运行中的程序,它指的是从代码加载,执行到执行结束这样一个完整过程.每个进程占用不同的内存空间. 线程   是进程中某个单一顺 ...

随机推荐

  1. c语言else匹配问题

    #include <stdio.h> #include <stdlib.h> //实现 依次输入三个递增的数 然后正确输出 //为什么得不到我们想要的结果呢 这就是else匹配 ...

  2. [iOS] 创建第一个应用程序项目

    开发环境:MacBook Pro XCode 5.0.1 1. 创建新的空的工程 2. 手动添加Controller 3. 将Controller添加到AppDelegate 4. 编辑.xib 5. ...

  3. Zedboard甲诊opencv图像处理(四)

    接着上一篇博客,继续改进,现在为了是图像处理结果更加稳定,我实在没有办法了,只好先提取手指,再提取指甲. 把手指从背景里面提出来还是挺简单的,可惜的是我研究这么半天还是这结果,好沮丧. 怎么办呢,时间 ...

  4. JavaScript深拷贝和浅拷贝

    1. 基本类型 和 对象类型 他们最大的区别就是在于他们的传值方式. 基本类型是传值 对象类型就是传引用. 这里复制一份obj叫做obj2, 这里修改了obj2的b为100 同时也修改了obj1.b. ...

  5. git 学习笔记一

    1.git的 介绍 分布式和 集中式 集中式版本控制系统最大的毛病就是必须联网才能工作,如果在局域网内还好,带宽够大,速度够快,可如果在互联网上,遇到网速慢的话,可能提交一个10M的文件就需要5分钟, ...

  6. Linux 运维笔记

    #配置静态地址网卡DEVICE="eth0"BOOTPROTO=staticHWADDR="00:0C:29:DC:EA:F7"NM_CONTROLLED=&q ...

  7. HTML与CSS入门——第九章 使用颜色

    知识点: 1.为网站选择颜色的方法 2.颜色在Web上的工作方式 3.使用十六进制颜色值的方法 4.使用CSS设置背景.文本和边框颜色的方法 9.1 选择颜色的最佳方法: 直白地说:根据用户群体找到最 ...

  8. 解决 innerHTML 在 IE6-IE9中不能赋值的bug

    在MSDN可以了解跟多,关于innerHTML的介绍,但是在这里只要是解决表格部分问题 MSDN上有这样的记录: When using innerHTML to insert script, you ...

  9. Java数据结构漫谈-ArrayList

    ArrayList是一个基于数组实现的链表(List),这一点可以从源码中看出: transient Object[] elementData; // non-private to simplify ...

  10. tomcat 支持https

    HTTP是平时浏览网页时候使用的一种协议.HTTP协议传输的数据都是未加密的,也就是明文的,因此使用HTTP协议传输隐私信息非常不安全.为了保证 这些隐私数据能加密传输,于是网景公司设计了SSL(Se ...