Same method in Interface and Abstract class

前端 未结 4 1469
一个人的身影
一个人的身影 2020-11-30 03:02

I came to situation :

public interface Intr {
    public void m1();
}

public abstract class Abs {
    public void m1() {
        System.out.println(\"Abs.m1         


        
4条回答
  •  猫巷女王i
    2020-11-30 03:25

    You can only override methods defined in another class.

    Methods declared in an interface are merely implemented. This distinction exists in Java to tackle the problem of multiple inheritance. A class can only extend one parent class, therefore any calls to super will be resolved without ambiguity. Classes however can implement several interfaces, which can all declare the same method. It's best to think of interfaces as a list of "must have"s: to qualify as a Comparable your cluss must have a compareTo() method but it doesn't matter where it came from or what other interfaces require that same method.

    So technically you override Abs.m1() and implement Intr.m1() in one fell swoop.

    Note that this would be fine too:

    public class B extends Abs implements Intr {
    
        //m1() is inherited from Abs, so there's no need to override it to satisfy the interface
    }
    

提交回复
热议问题