Can an abstract class have a constructor?

前端 未结 22 2179
甜味超标
甜味超标 2020-11-22 05:25

Can an abstract class have a constructor?

If so, how can it be used and for what purposes?

22条回答
  •  无人及你
    2020-11-22 06:07

    yes it is. And a constructor of abstract class is called when an instance of a inherited class is created. For example, the following is a valid Java program.

    // An abstract class with constructor
    abstract class Base {
    Base() { System.out.println("Base Constructor Called"); }
    abstract void fun();
        }
    class Derived extends Base {
    Derived() { System.out.println("Derived Constructor Called"); }
    void fun() { System.out.println("Derived fun() called"); }
        }
    
    class Main {
    public static void main(String args[]) { 
       Derived d = new Derived();
        }
    
    }
    

    This is the output of the above code,

    Base Constructor Called Derived Constructor Called

    references: enter link description here

提交回复
热议问题