Home Java javaTutorial Compare the differences between abstract classes and interfaces in Java

Compare the differences between abstract classes and interfaces in Java

Jul 20, 2017 pm 01:15 PM
java the difference interface

In the Java language, abstract class and interface are two mechanisms that support abstract class definition. It is precisely because of the existence of these two mechanisms that Java is given powerful object-oriented capabilities. There are great similarities between abstract class and interface in terms of support for abstract class definition, and they can even be replaced with each other. Therefore, many developers seem to be more casual about the choice of abstract class and interface when defining abstract classes. In fact, there is still a big difference between the two. The choice of them even reflects the understanding of the nature of the problem domain and whether the understanding of the design intention is correct and reasonable. This article will analyze the differences between them and try to provide developers with a basis for choosing between the two.

Understanding abstract classes

Abstract class and interface are both used to create abstract classes in the Java language (the abstract class in this article is not translated from abstract class. It represents an abstract body, and abstract class is a method used to define abstract classes in the Java language. Please pay attention to the distinction). So what is an abstract class? What benefits can using abstract classes bring us? ?

In the object-oriented concept, we know that all objects are represented by classes, but the reverse is not true. Not all classes are used to describe objects. If a class does not contain enough information to describe a specific object, such a class is an abstract class. Abstract classes are often used to represent the abstract concepts we derive from analysis and design of problem areas. They are abstractions of a series of specific concepts that look different but are essentially the same. For example: If we develop a graphics editing software, we will find that there are specific concepts such as circles and triangles in the problem domain. They are different, but they all belong to the concept of shape. The concept of shape is different in the problem domain. If it exists, it is an abstract concept. It is precisely because abstract concepts do not have corresponding concrete concepts in the problem domain, so abstract classes used to represent abstract concepts cannot be instantiated.

In the object-oriented field, abstract classes are mainly used for type hiding. We can construct an abstract description of a fixed set of behaviors, but this set of behaviors can have any number of possible concrete implementations. This abstract description is the abstract class, and this set of any possible concrete implementations is represented by all possible derived classes. Modules can operate on an abstract body. Because a module relies on a fixed abstraction, it cannot be modified; at the same time, the behavior of this module can also be extended by deriving from this abstraction. Readers who are familiar with OCP must know that in order to realize OCP (Open-Closed Principle), one of the core principles of object-oriented design, abstract classes are the key.

Look at abstract class and interface from the grammatical definition level

At the grammatical level, the Java language provides different definition methods for abstract class and interface. The following is to define one The abstract class named Demo is used as an example to illustrate this difference.
The way to define the Demo abstract class using abstract class is as follows:

1 abstract class Demo{2   abstract void method1();3   abstract void method2();4 …5 }
Copy after login

The way to define the Demo abstract class using interface is as follows:

1 interface Demo{2   void method1();3   void method2();4 …5 }
Copy after login

在abstract class方式中,Demo可以有自己的数据成员,也可以有非 abstract的成员方法,而在interface方式的实现中,Demo只能够有静态的不能被修改的数据成员(也就是必须是static final 的,不过在interface中一般不定义数据成员),所有的成员方法都是abstract的。从某种意义上说,interface是一种特殊形式的 abstract class。
  从编程的角度来看,abstract class和interface都可以用来实现 "design by contract" 的思想。但是在具体的使用上面还是有一些区别的。
  首先,abstract class 在 Java 语言中表示的是一种继承关系,一个类只能使用一次继承关系(因为Java不支持多继承)。但是,一个类却可以实现多个interface。也许,这是Java语言的设计者在考虑Java对于多重继承的支持方面的一种折中考虑吧。
  其次,在abstract class的定义中,我们可以赋予方法的默认行为。但是在interface的定义中,方法却不能拥有默认行为,为了绕过这个限制,必须使用委托,但是这会增加一些复杂性,有时会造成很大的麻烦。
  在抽象类中不能定义默认行为还存在另一个比较严重的问题,那就是可能会造成维护上的麻烦。因 为如果后来想修改类的界面(一般通过 abstract class 或者interface来表示)以适应新的情况(比如,添加新的方法或者给已用的方法中添 加新的参数时,就会非常的麻烦,可能要花费很多的时间(对于派生类很多的情况,尤为如此)。但是如果界面是通过abstract class来实现的,那 么可能就只需要修改定义在abstract class中的默认行为就可以了。
  同样,如果不能在抽象类中定义默认行为,就会导致同样的方法实现出现在该抽象类的每一个派生类中,违反了 "one rule,one place" 原则,造成代码重复,同样不利于以后的维护。因此,在abstract class和interface间进行选择时要非常的小心。

从设计理念层面看 abstract class 和 interface

  上面主要从语法定义和编程的角度论述了abstract class和interface的区 别,这些层面的区别是比较低层次的、非本质的。本小节将从另一个层面:abstract class和interface所反映出的设计理念,来分析一下二者的区别。作者认为,从这个层面进行分析才能理解二者概念的本质所在。
  前面已经提到过,abstract class在Java语言中体现了一种继承关系,要想使得继承关系合理,父类和派生类之间必须存在"is-a"关系,即父类和派生类在概念本质上应该是相同的。对于interface来说则不然,并不要求interface的实现者和interface定义在概念本质上是一致的, 仅仅是实现了interface定义的契约而已。为了使论述便于理解,下面将通过一个简单的实例进行说明。
  考虑这样一个例子,假设在我们的问题领域中有一个关于Door的抽象概念,该Door具有执行两个动作open和close,此时我们可以通过abstract class或者interface来定义一个表示该抽象概念的类型,定义方式分别如下所示:
  使用abstract class方式定义Door:

1 abstract class Door{2   abstract void open();3   abstract void close();4 }
Copy after login

     使用interface方式定义Door:

1 interface Door{
2   void open();
3   void close();
4 }
Copy after login

其他具体的Door类型可以extends使用abstract class方式定义的Door或者implements使用interface方式定义的Door。看起来好像使用abstract class和interface没有大的区别。
  如果现在要求Door还要具有报警的功能。我们该如何设计针对该例子的类结构呢(在本例中, 主要是为了展示 abstract class 和interface 反映在设计理念上的区别,其他方面无关的问题都做了简化或者忽略)?下面将罗列出可能的解 决方案,并从设计理念层面对这些不同的方案进行分析。
  解决方案一:
  简单的在Door的定义中增加一个alarm方法,如下:

1 abstract class Door{2   abstract void open();3   abstract void close();4   abstract void alarm();5 }
Copy after login

或者

1 interface Door{2   void open();3   void close();4   void alarm();5 }
Copy after login

那么具有报警功能的AlarmDoor的定义方式如下:

1 class AlarmDoor extends Door{2   void open(){…}3   void close(){…}4   void alarm(){…}5 }
Copy after login

或者

1 class AlarmDoor implements Door{2 void open(){…}3 void close(){…}4 void alarm(){…}5 }
Copy after login

这种方法违反了面向对象设计中的一个核心原则 ISP (Interface Segregation Principle),在Door的定义中把Door概念本身固有的行为方法和另外一个概念"报警器"的行为方 法混在了一起。这样引起的一个问题是那些仅仅依赖于Door这个概念的模块会因为"报警器"这个概念的改变(比如:修改alarm方法的参数)而改变,反之依然。

  解决方案二:
  既然open、close和alarm属于两个不同的概念,根据ISP原则应该把它们分别定 义在代表这两个概念的抽象类中。定义方式有:这两个概念都使用 abstract class 方式定义;两个概念都使用interface方式定义;一个概念 使用 abstract class 方式定义,另一个概念使用interface方式定义。
  显然,由于Java语言不支持多重继承,所以两个概念都使用abstract class方式定义是不可行的。后面两种方式都是可行的,但是对于它们的选择却反映出对于问题领域中的概念本质的理解、对于设计意图的反映是否正确、合理。我们一一来分析、说明。
  如果两个概念都使用interface方式来定义,那么就反映出两个问题:1、我们可能没有 理解清楚问题领域,AlarmDoor在概念本质上到底是Door还是报警器?2、如果我们对于问题领域的理解没有问题,比如:我们通过对于问题领域的分 析发现AlarmDoor在概念本质上和Door是一致的,那么我们在实现时就没有能够正确的揭示我们的设计意图,因为在这两个概念的定义上(均使用 interface方式定义)反映不出上述含义。
  如果我们对于问题领域的理解是:AlarmDoor在概念本质上是Door,同时它有具有报 警的功能。我们该如何来设计、实现来明确的反映出我们的意思呢?前面已经说过,abstract class在Java语言中表示一种继承关系,而继承关系 在本质上是"is-a"关系。所以对于Door这个概念,我们应该使用abstarct class方式来定义。另外,AlarmDoor又具有报警功能,说 明它又能够完成报警概念中定义的行为,所以报警概念可以通过interface方式定义。如下所示:

 1 abstract class Door{ 2   abstract void open(); 3   abstract void close(); 4 } 5 interface Alarm{ 6   void alarm(); 7 } 8 class Alarm Door extends Door implements Alarm{ 9   void open(){…}10   void close(){…}11   void alarm(){…}12 }
Copy after login

这种实现方式基本上能够明确的反映出我们对于问题领域的理解,正确的揭示我们的设计意图。其 实abstract class表示的是"is-a"关系,interface表示的是"like-a"关系,大家在选择时可以作为一个依据,当然这是建立在对问题领域的理解上的,比如:如果我们认为AlarmDoor在概念本质上是报警器,同时又具有Door的功能,那么上述的定义方式就要反过来了。

  小结
  1.abstract class 在 Java 语言中表示的是一种继承关系,一个类只能使用一次继承关系。但是,一个类却可以实现多个interface。
  2.在abstract class 中可以有自己的数据成员,也可以有非abstarct的成员方法,而在interface中,只能够有静态的不能被修改的数据成员(也就是必须是static final的,不过在 interface中一般不定义数据成员),所有的成员方法都是abstract的。
  3.abstract class和interface所反映出的设计理念不同。其实abstract class表示的是"is-a"关系,interface表示的是"like-a"关系。 
  4.实现抽象类和接口的类必须实现其中的所有方法。抽象类中可以有非抽象方法。接口中则不能有实现方法。
  5.接口中定义的变量默认是public static final 型,且必须给其初值,所以实现类中不能重新定义,也不能改变其值。抽象类中的变量默认是 friendly 型,其值可以在子类中重新定义,也可以重新赋值。 
  7.接口中的方法默认都是 public,abstract类型的。

  

 

The above is the detailed content of Compare the differences between abstract classes and interfaces in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

How to set password protection for export PDF on PS How to set password protection for export PDF on PS Apr 06, 2025 pm 04:45 PM

Export password-protected PDF in Photoshop: Open the image file. Click "File"> "Export"> "Export as PDF". Set the "Security" option and enter the same password twice. Click "Export" to generate a PDF file.

What is the difference between an abstract class and an interface in PHP? What is the difference between an abstract class and an interface in PHP? Apr 08, 2025 am 12:08 AM

The main difference between an abstract class and an interface is that an abstract class can contain the implementation of a method, while an interface can only define the signature of a method. 1. Abstract class is defined using abstract keyword, which can contain abstract and concrete methods, suitable for providing default implementations and shared code. 2. The interface is defined using the interface keyword, which only contains method signatures, which is suitable for defining behavioral norms and multiple inheritance.

What are the differences and connections between c and c#? What are the differences and connections between c and c#? Apr 03, 2025 pm 10:36 PM

Although C and C# have similarities, they are completely different: C is a process-oriented, manual memory management, and platform-dependent language used for system programming; C# is an object-oriented, garbage collection, and platform-independent language used for desktop, web application and game development.

How to use XPath to search from a specified DOM node in JavaScript? How to use XPath to search from a specified DOM node in JavaScript? Apr 04, 2025 pm 11:15 PM

Detailed explanation of XPath search method under DOM nodes In JavaScript, we often need to find specific nodes from the DOM tree based on XPath expressions. If you need to...

Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Apr 05, 2025 pm 01:03 PM

The necessity of registering VueRouter in the index.js file under the router folder When developing Vue applications, you often encounter problems with routing configuration. Special...

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The difference in output results of console.log: Why do the same variables have different printing methods but different results? The difference in output results of console.log: Why do the same variables have different printing methods but different results? Apr 04, 2025 am 11:48 AM

In-depth discussion of the differences in console.log output in this article will analyze the reasons why the output results of console.log function in a piece of code are different. Code snippets involve URL parameter resolution...

See all articles