Abstract class vs Interface

Source: Internet
Author: User

Abstract class vs Interface

Differences

  1. Abstract class methods can have method bodies, while interface methods cannot have method bodies.
  2. Methods in abstract classes. If abstract modifier is not added, the method body must be defined.
  3. Class can implement multiple interfaces, but can inherit only one abstract class
  4. All interfaces are public, while abstract classes can set their own permissions. However, the abstract method of an abstract class cannot be set to private.
  5. The interface member must be initialized, but the abstract class does not.
  6. Abstract classes can implement interfaces, but interfaces cannot implement interface examples.

    public interface Car {int price = 1;void run();}public abstract class AbstractCar {int price;public void run(){System.out.println("hh");}abstract void stop();}

    Application scenarios
      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 hassystemic. 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.

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.