About the reasons for constants and variable definitions in abstract classes and interfaces in Java

Source: Internet
Author: User

Reprinted from https://my.oschina.net/cdzsc/blog/86107

In an abstract class, you can include one or more abstract methods, but in an interface (interface), all methods must be abstract and cannot have a method body, which is more "abstract" than an abstract class.

1. Why only static final is defined in an interface:

1.1 static (which is considered a variable at this moment) explains: because a class can implement multiple interfaces, if a class implements multiple interfaces at the same time, and each interface defines the same variable, it produces a variable in the class that does not know which interface it is. So it has to be defined as static, and each interface has its own variable.

1.2 Final explanation: because an interface can be implemented by multiple classes, if it is not defined as final, each class that implements the interface changes the variable to produce an error, so it must be defined as final.

 Public Interface number of satahdd{    // cables public    staticfinalint connect_line=4;     // Write Data     Public void WriteData (String data);     // Read Data     Public String readdata ();}

Note: The member variables declared in the interface are public static final by default and must be displayed for initialization. Thus, these modifiers can be omitted at constant declarations.

2. Why variables can be defined in an abstract class:

Because each class can have only one parent class, it does not produce some of the problems in the above interfaces.

About the reasons for constants and variable definitions in abstract classes and interfaces in Java

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.