0

I am a beginner in Java. I have a question about the abstract method in Interface. Is the following sampleMethod() an abstract method? My understanding is that it is not an abstract method due to System.out.println. Am I correct?

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

Thanks in advance!

Lei
  • 11
  • 1
    A _default_ method is by definition not _abstract_. Default methods were added to Java in version 8 and can only be declared in interfaces. If your method was declared like `void sampleMethod();`, then it would be abstract (implicitly, due to it being declared in an interface, though you could explicitly add the `abstract` keyword). As you can see, an abstract method cannot _do_ anything, as it has no method body. – Slaw Jun 27 '22 at 20:36
  • 1
    That is a default method on an interface not an abstract method on an abstract class. https://stackoverflow.com/questions/19998454/when-to-use-java-8-interface-default-method-vs-abstract-method#:~:text=These%20two%20are%20quite%20different,are%20intended%20to%20be%20extended. – bhspencer Jun 27 '22 at 20:37

1 Answers1

0

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. 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();
}