简体   繁体   English

抽象方法可以做 System.out.println 吗?

[英]can abstract method do System.out.println?

I am a beginner in Java.我是Java的初学者。 I have a question about the abstract method in Interface.我对接口中的抽象方法有疑问。 Is the following sampleMethod() an abstract method?以下sampleMethod()是抽象方法吗? My understanding is that it is not an abstract method due to System.out.println .我的理解是,由于System.out.println ,它不是抽象方法。 Am I correct?我对么?

default void sampleMethod() {
            System.out.println("Am I abstract method?");
}

Thanks in advance!提前致谢!

The sampleMethod() isn't an abstract method it is a default methode, which means that you can call this Methode at any implementation, because this is the default methode which will be called. sampleMethod()不是抽象方法,它是默认方法,这意味着您可以在任何实现中调用此方法,因为这是将被调用的默认方法。 Furthermore you can override this methode in your implementation but if you do not it wil simply call your default methode from the interface.此外,您可以在您的实现中覆盖此方法,但如果您不这样做,它只会从接口调用您的默认方法。 So you don't have to override/implement it in your implementation class.所以你不必在你的实现类中覆盖/实现它。

But keep in mind that even with a default methode in your interface you can't manage any variables if you wont to do this use an abstract class like this但请记住,即使在您的界面中使用默认方法,您也无法管理任何变量,如果您不想这样做,请使用这样的抽象类

public abstract class SomeAbstractClass{
    String thing;

    protected SomeAbstractClass(String thing) {
        this.thing = thing;
    }

    void sampleMethod() {
        System.out.println(thing);
        //or do other stuff
    }

    abstract void otherMethode();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM