-1

`In jav8, We are supporting Constructor in abstract class. why we need Constructor in abstract class, if we are having static and non-static block support

Code :-

abstract class a{
    static
        {
            System.out.println("Inside Abstarct class static");
        }
    {
        System.out.println("Inside Abstarct class");
    }
    a(){
        System.out.println("Inside Abstarct class Constructor");
    }
    abstract void play();
}
class b extends a{
    public void play(){
        System.out.println("Inside b class");
    }
}

Instantiation :- b b1=new b(); b1.play();

output:- Inside Abstarct class static Inside Abstarct class Inside Abstarct class Constructor Inside b class

Detail Explanation of why we need Constructor in abstract class?`

jps
  • 20,041
  • 15
  • 75
  • 79
  • 2
    Same reason for needing a constructor in non-abstract classes: Because you can perform initialization in the constructor (note instance initializer blocks are simply folded into the constructor at compile time; and note if you don't define a constructor explicitly, then a default one is provided implicitly), and because perhaps the abstract class needs to be given arguments when instantiated. – Slaw Apr 15 '23 at 05:51
  • 1
    BTW that is not only in Java 8, I *believe* that was always the case for every version; BTW2 description of the [tag:core] tag: "*Use this tag to refer to processor cores or questions related to threads and parallel processing.*" – user16320675 Apr 15 '23 at 06:36
  • Also see [Constructor in Java Abstract Class](https://www.geeksforgeeks.org/constructor-in-java-abstract-class/) on GeeksforGeeks. Did you remember to search thoroughly before posting your question? – Ole V.V. Apr 15 '23 at 09:05

1 Answers1

2

Why wouldn't you need a constructor?

You still might want to do

abstract class Foo {
  int a;
  Foo(int a) {
    this.a = a;
  }
}

You still need constructors for all the same reasons as other classes do.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413