开发者

Puzzling explanation on abstraction vs interface in java doc

开发者 https://www.devze.com 2023-01-29 03:07 出处:网络
In java document, it is said : Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain

In java document, it is said :

Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods.

Is that a correct text? that not part confuses me because interfaces don't have static or final fields, right?

Source : http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

Thanks.

Edit :

public interface GroupedInterface extends Interface1,
                                        Interface2, Interface3 {

   // const开发者_如何学JAVAant declarations
   double E = 2.718282;  // base of natural logarithms

   // method signatures
   void doSomething (int i, double x);
   int doSomethingElse(String s);

}

An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.


Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

from section 9.3 of the Java Language Specification (here)


Click on "Defining an Interface" on the link in your question:

An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.


That is the correct text.

All fields in an interface are inferred to be public, static and final, whether or not explicitly so declared. Just as all methods are public and abstract, whether or not so declared.


the think is.. all fields inside an interface will be static and final, even if you didnt write the static and final!


The documentation is correct. Interfaces may contain static final fields to be used as constants. Abstract classes may contain instance variables to be inherited by extending classes. Those variables are then available in instances of the extending classes.


The quote is correct. Interfaces can have static final fields, but cannot have any other combination (non-static or non-final).

Fields on an interface are static and final by default, adding the modifiers is not necessary because there's no alternative.

For an abstract class it can make sense to give it mutable state, see java.util.AbstractList. Interfaces are not allowed to have any member that would confer mutable state on a class implementing it.

0

精彩评论

暂无评论...
验证码 换一张
取 消