Overriding parameterized constructors in subclasses in java

I am just starting my story with Java, however I have experience with OOP 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 I expect, since the required constructors are already defined in the base class, there is no need to define another constructor. Why do I need to define one for the subclass, as they do nothing special but call super()? Is there some special reason why the java compiler wants me to define a constructor in a child class?

+4
source share
5

, .

Java , , ( new B()).

B , , :

public B(Map dict) {
    super(dict);
}
+4

Parametrised B super , - B.

- :

import java.util.*; 

class B extends A
{
    B(Map dict) {
         super(dict);
     }
}
+1

Java - A- , B- . , A 0 - - . , super(). :

public class A {
    public A(int something) {

    }
}

public class B extends A {
    public B(int something) {
        super(something);
    }
}

public class C extends A {
    public C() {
        super(999);
    }
}

//--------------------------------------------//

public class A {
    public A() {

    }
}

public class B extends A {
    public B(int something) {
        super();
    }
}

public class C extends A {
    public C(int something) {
    }
}

public class D extends A {
    public D() {
        super();
    }
}

public class E extends A {
    public E() {

    }
}
+1

. B, .

class B extends A
{
    B(){
      super();  // calling super class  default constructor
    }
    B(Map dict) {
        super(dict); // calling super class single parameter(map) constructor
    }
}

,

B b = new B(); //invokes A Default Constructor
B b = new B(d); //invokes A Parameter Consturctor

, .

+1

? , , , , , , , , , Utility, .

0

Source: https://habr.com/ru/post/1655797/


All Articles