Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overriding parameterized constructors in sub-classes in java

i'm just beginning my story with Java, however I have some OOP experience with Python. I have the following class hierarchy :

class A {
   public A() {};
   public A(final java.util.Map dict) {};
}

class B extends A {
}

public class Main {
  public static void main() {
     java.util.Map d = new java.util.HashMap();
     B b = new B(d);
  }
}

The attached code causes the following error:

Main.java:16: error: constructor B in class B cannot be applied to given types;
     B b = new B(d);
           ^
  required: no arguments
  found: Map
  reason: actual and formal argument lists differ in length
1 error

What my expectation is, since required constructors are already defined in the base class, is no-need to define another constructor. Why do I need to define one for sub-class, since they don't do any thing special, apart from calling super() ? Is there any special reason, why java compiler wants me to define constructor in child class ?

like image 941
Mangu Singh Rajpurohit Avatar asked Mar 12 '23 01:03

Mangu Singh Rajpurohit


2 Answers

When you instantiate a class, a constructor of that class must be invoked.

When a Java class has no constructor, the compiler automatically generates a parameter-less constructor, which allows you to instantiate the class with no parameters (in your example, it allows new B()).

Since you try to instantiate your B class with a parameter, you must declare an appropriate constructor which invokes the super class constructor of your choice :

public B(Map dict) {
    super(dict);
}
like image 130
Eran Avatar answered Apr 27 '23 20:04

Eran


You need to declare the Parametrised constructor in your class B and call super from it if you don't want to initialize any thing in your class B.

Something like :

import java.util.*; 

class B extends A
{
    B(Map dict) {
         super(dict);
     }
}
like image 38
Sibaditya Maiti Avatar answered Apr 27 '23 22:04

Sibaditya Maiti