Java inheritance and interfaces, Java inheritance Interfaces

Source: Internet
Author: User

Java inheritance and interfaces, Java inheritance Interfaces

The most critical role of an interface is also the most important reason for using an interface: it can be traced to multiple basic classes. The second reason for using an interface is the same as that for using an abstract basic class: prevent the client programmer from making an object of this class and stipulate that it is only an interface. This raises the question: should I use an interface or an abstract class? If an interface is used, the benefits of abstract classes and interfaces can be obtained at the same time. Therefore, if the basic class to be created does not have any method definition or member variables, you are willing to use the interface regardless of the method, rather than the abstract class. In fact, if you know that something will become a basic class, the first choice is to turn it into an interface. Abstract classes should be considered only when method definitions or member variables must be used.

/*** Created by xfyou on 2016/11/3. * Java inheritance and interface demonstration */public class Adventure {static void t (CanFight x) {x. fight ();} static void u (CanSwim x) {x. swim ();} static void v (CanFly x) {x. fly ();} static void w (ActionCharacter x) {x. fight ();} public static void main (String [] args) {Hero I = new Hero (); t (I); u (I); v (I ); w (I) ;}} interface CanFight {void fight ();} interface CanSwim {void swim () ;}interface CanFly {void fly ();} class ActionCharacter {// The interface method inherited from the subclass is implemented in the parent class public void fight () {}}/*** must first extends and then impplements */class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly {@ Override public void fly () {}@ Override public void swim (){}}

 

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.