The same method as the parent interface is defined in the Java sub-interface

Source: Internet
Author: User

Today comes a very interesting question: what happens in Java if a subinterface defines a method that already exists in the parent interface? Like what:

Interface Irunnable extends runnable{void run ();

At first I thought that the syntax of this kind of grammar should not be passed through the compiler, and did not expect this to be the compiler did not make any warning.

Of course we wouldn't do it in most cases, because it doesn't seem to make much sense. But for the truth, I made a small realization:

public class Interfacedebug{public static void Main (string[] args) {irunnable irun1=new irunnableimpl (); Irun1.run (); Runnable Irun=irun1;irun.run (); irun=new IRunnableImpl2 (); Irun.run ();}} Interface Irunnable extends runnable{void run (); Class Irunnableimpl implements Irunnable{public void Run () {System.out.println ("irunnable of Irunnableimpl");}} Class IRUNNABLEIMPL2 implements Runnable{public void Run () {System.out.println ("irunnable of IRunnableImpl2");}}

The result of the operation is:

Irunnable of Irunnableimplirunnable of irunnableimplirunnable of IRUNNABLEIMPL2

As you can see, the Run method defined in Irunnable is actually run in runnable, and they both refer to the same thing and do not overwrite the method.

The same method as the parent interface is defined in the Java sub-interface

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.