0

I want the parameterized constructor(Constructor of choice) of the parent class to be called during inheritance.

But by default I'm getting the un-parameterized constructor.

class parent
{

    parent(int i){System.out.println("From parameterized constructor");}
    parent(){System.out.println("From Normal Constructore");}
}

class child extends parent
{
    child()
    {
    System.out.println("From child");
    }
}


public class MyClass {
    public static void main(String args[]) {
        child c=new child();
    }
}
  • Can you please define what a parameterized constructor is? How is it different from a constructor? – scottb Oct 12 '17 at 14:01
  • Have you read into the `super()` command? It's used to initialize variables that the parent class would have. Plus, you are creating a child class with the constructor with no parameters. – Michael Platt Oct 12 '17 at 14:01
  • Take care of the Java naming conventions. Class names should start with an uppercase letter – Jens Oct 12 '17 at 14:02
  • You use `super(5)` for example. In other words: A) you do some more research B) ... you simple pass the required parameter ;-) – GhostCat Oct 12 '17 at 14:02

2 Answers2

6

By default every constructor contains a call to super() as the first line unless specifically overridden. So in your case;

Child() {
    System.out.println("From child");
}

is equivalent to

Child() {
    super();
    System.out.println("From child");
}

Where super() is a reference to the default constructor of the parent class. To change it. You can do something like the following;

Child() {
    super(1);
    System.out.println("From child");
}

This should output something like

From parameterized constructor
From child
Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
  • 1
    Beat me to it. Keep this in mind: you want to use a specific constructor, you need to actually call it. – Michael Peacock Oct 12 '17 at 14:03
  • FYI: you may want a constructor for your `child` class that is parametrized as well. The parameters need to come from somewhere and `super()` always has to be called in the first line. And one last tip: it is good practice to use capital letters for classes: `Child` instead of `child`. Then expressions like `Child child = new Child()` will be possible. – GameDroids Oct 12 '17 at 14:10
2

If you won't specify any constructor, it will take the default one (parameterless).
If you want a different one, you can call it by calling super:

child() {
    super(1);
    System.out.println("From child");
}
Nir Levy
  • 12,750
  • 3
  • 21
  • 38