Inherit the interface and implement multiple interfaces

Pay attention when using the interface, you need to pay attention to:

1. There is no static code block or construction method in the interface .

Knowledge points recall: the typical use of static code blocks-used to assign values ​​to static member variables at once. When this class is used for the first time, the static code block is executed only once , which is better than the non-static code block.

You can't write a construction method, you can write new.

2. The direct parent of a class is unique, but a class can implement multiple interfaces at the same time.

format:

public clas MyInterfaceImpl implements MyInterfaceA,MyInterfaceB{

     // Overwrite all abstract methods

}

public interface MyInterfaceA {
    public abstract void methodA();
}
public interface MyInterfaceB {
    public abstract void methodB();
}
public class Demo06Interface implements MyInterfaceA,MyInterfaceB{ 
    @Override 
    public void methodA() { 
        System.out.println("Override overrides the A abstract method"); 
    } 

    @Override 
    public void methodB() { 
        System.out.println("Override Rewrite the B abstract method"); 
    }

}

3. If there are repeated abstract methods among the multiple interfaces implemented by the implementation class , you only need to override and rewrite once.

@Override 
public void method() { 
    System.out.println("Override and rewrite the abstract methods of the A and B interfaces"); 
}

4. If the implementation class does not override all abstract methods in all interfaces, then the implementation class must be an abstract class.

5. If there are duplicate default methods among the multiple interfaces implemented by the implementation class, the implementation class must override the conflicting default methods .

A、B

public default void methodDefault(){
}

Implementation class:

@Override 
public void methodDefault() { 
    System.out.println("Override the abstract method that rewrites the conflict between A and B"); 
}

6. If a method in a direct parent class conflicts with the default method in the interface, the method in the parent class will be used first.

public class Fu { 
    public void method(){ 
        System.out.println("The member method of the parent class"); 
    } 
}
public interface MyInterface { 
    public default void method(){ 
        System.out.println("The default method of the interface"); 
    } 
}
public class Zi extends Fu implements MyInterface{
}
Zi zi = new Zi (); 
zi.method ();

Run screenshot:

 

Guess you like

Origin blog.csdn.net/wardo_l/article/details/113851600