Interfaces

Interfaces and abstract classes provide a more structured way to separate interface from implementation

abstract Classes and Methods

Abstract method has only a declaration and no method body. If a class contains one or more abstract methods, the class itself must be qualified as abstract, otherwise the compiler gives an error message.

  • You cannot create an object of an abstract class.
  • If you inherit from an abstract class and you want to make object of the new type, you must provide method definitions for all the abstract methods in the base class.
  • If you don't implement those abstract methods, the derived class should be declared as abstract.
  • It's possible to make a class abstract without including any abstract methods.

The reason to use abstract classes and methods:

  • They make the abstractness of a class explicit, and tell both the user and compiler how it was intended to be used.
  • They are useful refactoring tools, since they allow you to easily move common methods u the inheritance hierarchy.

Interfaces

The interface keyword produces a completely abstract class (no implementation at all). It allows the creator to determine method names, argument lists, and return types, but no method bodies. However, an interface is more than just an abstract class  taken to the extreme, since it allows you to perform a variation of "multiple inheritance" by creating a class that can be upcast to more than one base type.

  • As with a class, you can add the public keyword before the interface keyword. If you leave off the public keyword, you get package access, so the interface is only usable within the same package. 
  • Methods in an interface are implicitly public. So when you implement an interface, the methods from the interface must be defined as public. Otherwise, they would default to package access, and you'd be reducing the accessibility of a method during inheritance., which is not allowed by the Java compiler.
  • An interface can also contain fields, but these are implicitly static and final.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值