Differences between abstract classes and interfaces

Source: Internet
Author: User

 

1Abstract classes and interfaces cannot be directly instantiated. to instantiate an abstract class, the variable must point to the subclass object that implements all abstract methods, and the interface variable must point to the class object that implements all interface methods.

 

2Abstract classes must be inherited by quilt classes, and interfaces must be implemented by classes.

 

3The interface can only be used for method declaration. The abstract class can be used for method declaration or method implementation.

 

4The variables defined in the interface can only be public static constants, and the variables in the abstract class are common variables.

 

5Abstract METHODS in abstract classes must be implemented by all quilt classes. If not all child classes can implement the parent class abstract methods, this child class can only be an abstract class. Similarly, if an interface cannot be fully implemented, the class can only be an abstract class.

 

6Abstract METHODS can only be declared and cannot be implemented.Abstract void ABC ();Cannot be writtenAbstract void ABC (){}.

 

7Abstract classes can have no abstract methods

 

8If an abstract method exists in a class, the class can only be an abstract class.

 

9Abstract methods must be implemented, so they cannot be static or private.

 

10Interfaces can inherit interfaces and can inherit multiple interfaces

 

So when to use inheritance and when to use interfaces?

Java Interfaces are used to share common behaviors among different class instances. (Method header only).

Inheritance is used to share common code in related class instances. (Including data members and Methods)

In your program design, remember to useJavaInterfaces share common behaviors. Use inheritance with common code .

 

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.