The difference between abstract classes and interfaces in Java (abstract class VS interface)

Source: Internet
Author: User

The problem that this paper solves

    • What is abstract class
    • Application Scenarios for abstract classes
    • Can interfaces be implemented in a method?
    • The difference between an interface and an abstract class
1 What is abstract class

When declaring a keyword abstract is a class, abstract class it can be regarded as a template of a concrete class, inheriting its subclasses can share some methods (possibly incomplete) and properties from the abstract class.

A class which is declared with the abstract keyword are known as an abstract class in Java. It can have an abstract and Non-abstract methods (method with the body). N abstract class represents an abstract concept or entity with partial or no implementation. Therefore, Abstract Classes act as parent classes from which child classes is derived so, the child class would share The incomplete features of the parent class and functionality can be added to complete them.

Precautions are:

    • Abstract classes can not be instantiated
    • An abstract class is essentially a class, so it can have constructors and static methods.
    • Abstract classes can have abstract methods and non-abstract methods
    • Abstract classes can have a final method, and subclasses cannot be changed
2 usage scenarios for abstract Classes 2.1 Use Example 1
//定义抽象类    public abstract class AbstractClass {    int age;    String gender;        public AbstractClass() {//构造器        System.out.println("I‘m abstract class.");    }       public void nonAbstract() {        System.out.println("I am non abstract method in the abstract class.");    }       abstract public void print();//抽象方法}public class AbstractClassTest extends AbstractClass {//继承了抽象类        public void print() {  //实现了抽象类的方法        System.out.println("I override from abstract class");        }        public static void main(String[] args) {        AbstractClassTest test = new AbstractClassTest();        test.nonAbstract();//继承自抽象类的方法        test.print();    }}

Results
I ' M abstract class.
I am Non abstract method in the abstract class.
I override from abstract class

As can be seen from the above example, abstract classes can have constructors, abstract methods and non-abstract methods, and can have variables. Non-abstract methods, subclasses can inherit directly, whereas abstract method subclasses must be implemented.

2.2 Using Scene 1
abstract class Shape{    abstract void draw();}class Circle extends Shape{    public void draw() {        System.out.println("draw a circle.");    }}class Rectangel extends Shape{    public void draw() {        System.out.println("draw a rectangel.");    }}class Dimond extends Shape{    public void draw() {        System.out.println("draw a dimond.");    }}public class AbstractTest2 {        public static void main(String[] args) {        Shape shape = new Circle();        shape.draw();                shape = new Rectangel();        shape.draw();                shape = new Dimond();        shape.draw();    }}

Run results
Draw a circle.
Draw a Rectangel.
Draw a Dimond.

You can use abstraction as a template, declare an abstract class, and refer to any specific subclass.

3 What is an interface

An interface is also a reference type, defined when using the interface keyword, when it is a collection of abstract methods. An interface can define a variable of the final type. Before jkd1.8, the interface can not have the implementation of the concrete method, jkd1.8 after the interface may have Defaul method body and the static square body.

An interface are an abstract type that's used to specify a contract this should be implemented by classes, which implement That interface. The interface keyword is used to define an interface and Implements keyword are used for implementing an interface by a CLA SS (in Java programming language).

4 Interface Implementation Note The default method in the Point 4.1 interface

Why join the DEFAULT keyword
In the past, when we wanted to add new methods to the interface, all the methods that had implemented the interface had to be rewritten, and the new method was re-implemented. To address this problem, the default keyword was introduced. Default does not force a class that implements the interface to re-implement a method that contains a default signature.

Example

public interface Interface1 {    void method1(String str);//方法签名        default void log(String str){ //default 方法        System.out.println("logging::"+str);    }}public class InterfaceTest1 implements Interface1 {    @Override    public void method1(String str) {        System.out.println("implement the method in interface1 "+str);    }    public static void main(String[] args) {        InterfaceTest1 test = new InterfaceTest1();        test.log("abc"); //接口中的default方法        test.method1("abc");    }}

Run results

Logging::abc
Implement the method in Interface1 ABC

Analysis: The log method is the default method in the interface, does not enforce its subclass INTERFACETEST1 implementation of the method, but the modification method can be inherited. A summary of the default method is as follows:

    • The default method in the interface can help extend the interface without worrying about changing the implementation of the original class
    • The default method actually narrows the distinction between interfaces and abstract classes
    • If a class has the same signature as the default method, the default method is ignored, that is, the method in the called Time class
Static methods in the 4.2 interface

After JAVA8, the interface can have a static method, but it cannot be overridden and cannot be inherited by a subclass that implements it.

Example

    public interface Interface2 {    default void print(String str) {        if (!isNull(str))            System.out.println("MyData Print::" + str);    }    static boolean isNull(String str) {//static 方法        System.out.println("Interface Null Check");        return str == null ? true : "".equals(str) ? true : false;    }}public class InterfaceTest2 implements Interface2{        public boolean isNull(String str) { //仅仅是简单的类方法,不是override接口里面的isNull        System.out.println("Impl Null Check");        return str == null ? true : false;    }    public static void main(String[] args) {        InterfaceTest2 obj = new InterfaceTest2();        obj.print("");        obj.isNull("abc");            }}

Run results
Interface Null Check
Impl Null Check

Analysis: Obj.print () invokes the default method in the interface, and the Print method in the interface first invokes the static method IsNull in the interface, so the output interface Null Check, and then the Obj.isnull ("abc") is executed. ), because the implementation class has the same method as the signature in the interface, the default method in the signature is overwritten, the IsNull in the class method is called, and the output Impl Null Check. If the method IsNull in the interface is the default type, what will it output? As follows:
Impl Null Check
MyData Print::
Impl Null Check

The static method in the interface is summarized as follows:

    • The static method in the interface is part of the interface and cannot be used outside
    • The static methods in the interface can be used to provide some utinity methods, such as checking non-null, sorting, etc.
5 differences between abstract classes and Interfaces 5.1 syntax is different
    • The easiest thing to think about is the abstract class that is used when the syntax is different, and the interface used by the interface;
    • The keywords used when inheriting the two are different, abstract with extends, and interface with implments;
    • The inheritance number is different, the class in Java is single inheritance, a class can inherit only one abstract class, but can implement multiple interfaces;
    • The inherited method is not exactly the same, the subclass inherits the abstract class, it is necessary to implement the method in the abstract class, otherwise the subclass must also be declared abstract class, or the compilation error, the subclass implements the interface, also must implement the method signature in the interface, or compile an error. There is no way to implement an interface in a subclass, at which point the class becomes a sub-interface, or the handle class becomes an abstract class.
    • Internal structure is different, abstract class can be various variables, constructors, method body, method declaration; The variables in the interface can only be final, and the method body can only be modified by static or default after JAVA8.
    • The method in the interface cannot be said to be private.
5.2 Different usage scenarios

Abstract class
Abstract classes are generally used to provide some basic common behavior or methods, and for framework applications, abstract classes are a better choice.
Interface
If the design may change later, or the frequency is higher, the interface is more appropriate and easier to expand.



Reference reading
Https://www.javatpoint.com/abstract-class-in-java
https://www.differencebetween.com/difference-between-abstract-class-and-vs-interface/
Https://www.javaworld.com/article/2077421/learn-java/abstract-classes-vs-interfaces.html

The difference between abstract classes and interfaces in Java (abstract class VS interface)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.