2

Why does abstract class support static and instance block and interface does not? An abstract class also supports a constructor even though we can't instantiate an abstract class.

abstract class Abs{
    final int x;
    final int y;
    final static int z;

    public Abs(){
        x=10
    }

    {
        y=10;
    }

    static{
        z=10;
    }
}

In above code, I'm initializing a variable at run time, but the same thing is not applicable with interface. Why?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ashwini Pandey
  • 115
  • 2
  • 2
  • 9
  • An interface is not a class, it does not have a constructor, variables or any code but method signatures, except from `default` method implementations since Java 8. – deHaar Nov 16 '18 at 09:34
  • interface has variable also with default modifier public static and final. and if interface not a class then why .class file generate after compilation – Ashwini Pandey Nov 16 '18 at 09:39
  • See also [What is the difference between an interface and abstract class?](https://stackoverflow.com/questions/1913098/what-is-the-difference-between-an-interface-and-abstract-class) – Mark Rotteveel Nov 17 '18 at 08:20

2 Answers2

3

Interface as it's name suggests is primarily meant for defining contract and not implementation(before Java 8) but you are allowed to initialise fields.

However you can have a nested class or enum which has as much code as you like.

Dark Knight
  • 8,218
  • 4
  • 39
  • 58
1

Interface

Do not have constructor or initialization blocks, because you cannot create instance of interface (only with implemented class). All variables are public static final and all methods are public. Method could have default implementation with default keyword.

Abstract class

This is normal class, but you cannot create instance of this class. But they have any variables, static blocks and constructors (public constructors are useless, becuase only nested classes could call it, so it is reccomenended to mark all constructor protected).

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35