Wednesday, August 21, 2019

Can we override constructor in java?

Problem statement:
You are given a code for constructor overriding. What do you think, can we override the constructor in java?

Ans: No.
  1. class A {
  2. A() {
  3. System.out.println("A of A");
  4. }
  5. }
  6. class B extends A {
  7. A() {
  8. System.out.println("A of B");
  9. }
  10. }
  11. public class Sample {
  12. public static void main(String[] args) {
  13. B b = new B();
  14. }
  15. }
Output:
Return type of method is missing, meaning compiler is treating A() as a method not as a constructor and also compiler is expecting return type for the method A(), because in code there is no return type.

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...