Home java Calling a constructor from a constructor

Calling a constructor from a constructor

Author

Date

Category

I can’t figure out how to do this, help who knows.

I know it’s elementary, but still:

there are two constructors, one constructor (no arguments) must call the second constructor (with an argument of type int ).

public class MyInitTest {
  private String a;
  private double c;
  {
    a = "non-static initialization block";
    System.out.println (a);
  }
  {
    c = 20.03652;
    System.out.println (c + a);
  }
  static private String string;
  static private int anInt;
  static {
    string = "Static block";
    System.out.println (string);
  }
  static {
    anInt = 6;
    System.out.println (anInt + "Static block");
  }
  public MyInitTest () {
  }
  public MyInitTest (int) {
  }
}

Answer 1, authority 100%

public class Privet {
  public Privet () {
    this (1); // This constructor calls the constructor with a parameter
  }
  public Privet (int a) {
    // ...
  }
}

Answer 2, authority 93%

public class MyInitTest {
  public MyInitTest () {
    this (1); // call the second constructor
  }
  public MyInitTest (int i) {
    // ...
  }
}

Answer 3, authority 100%

If you need to call the constructor of the parent class, then

super (7);

if another constructor of the current class, then

this (8);

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions