Q:

Java program to create an abstract class with the constructor

belongs to collection: Java Abstract Class Programs

0

Java program to create an abstract class with the constructor

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to create an abstract class with a constructor is given below. The given program is compiled and executed successfully.

// Java program to create an abstract class 
// with the constructor

abstract class AbsClass {
  abstract void MyFun();

  AbsClass() {
    System.out.println("AbsClass: constructor called");
  }
}

class Sample extends AbsClass {
  Sample() {
    System.out.println("Sample: constructor called");
  }

  void MyFun() {
    System.out.println("Sample: MyFun() called");
  }
}

public class Main {
  public static void main(String[] args) {
    AbsClass abs = new Sample();
    abs.MyFun();
  }
}

Output:

AbsClass: constructor called
Sample: constructor called
Sample: MyFun() called

Explanation:

In the above program, we created an abstract class AbsClass with an abstract method and constructor. Then we will inherit the AbsClass into Sample and implemented the MyFun() method.

The Main class contains a method main(). The main() method is the entry point for the program, here we created a reference of AbsClass and initialized it with the reference of Sample class. Then the constructor of AbsClass and MyFun() gets called. After that, we called MyFun() method using the reference of AbsClass.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to create an abstract class without a... >>
<< Java program to create a simple abstract class...