-6

I recently began to wonder, why would I ever use an abstract class, when i could just do an interface with the exact same functionality. Consider the following:

abstract class abstractClass {

    public int a;

        public void printText(String str) {
        System.out.println(str);
    }
}

If I had a subclass extending this, I would be sure to have an integer a and a method named printText.

interface Interface{

    public int a = 0;

    public default void printtext(String str) {
        System.out.println(str);
    }
}

If I had a class implement this, I would be sure to have an integer a and a method printText.

So, the only difference I see is that with the interface, any class I create would be able to implement as many other interfaces as I would like, but with the extension of the abstract class, I would not be allowed to extend more classes. Why would I ever go for the abstract class? I hope this question isn't too broad, although I can see why some would consider it that.

Joe Sebin
  • 452
  • 4
  • 24

1 Answers1

1

A few points to consider:

  1. Interfaces didn't have default methods until Java 8.

  2. That a in your interface is implicitly final. Interfaces can't define public mutable fields.

  3. Interfaces can't define private (or protected, or package) fields.

  4. Interfaces can't have protected or package methods; they couldn't have private methods until Java 9.

Abstract classes don't have any of those issues. So when you need to do any of those things (other than #1, now that default methods exist), you reach for an abstract class (perhaps in addition to an interface that it implements).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    since Java 9, interfaces can have private methods. – Anton Balaniuc Jun 07 '18 at 11:19
  • @AntonBalaniuc - Doh! I'd seen that, too, but managed to forget. Thanks. But still not protected or package, right? (They'd need a new keyword for package, since leaving off `public` wouldn't do it...) – T.J. Crowder Jun 07 '18 at 11:30