OCA Java SE 8 Mock Exam Review - OCA Mock Question 30








Question

Examine the following code and select the correct options:

public class Main {
  public Main() {
    this(7);
    System.out.println("public");
  }

  private Main(int val) {
    this("Sunday");
    System.out.println("private");
  }

  protected Main(String val) {
    System.out.println("protected");
  }

  public static void main(String[] args) {
    Main print = new Main();
  }
}

a  The class Main defines three overloaded constructors. 
b  The class Main defines two overloaded constructors. 
   The private constructor is not an overloaded constructor. 
c  Constructors with different access modifiers can't call each other. 

d  The code prints the following: 

                protected 
                private 
                public 

e  The code prints the following: 

                public 
                private 
                protected 




Answer



A, D

Note

You can define overloaded constructors with different access modifiers.

private methods and constructors are also counted as overloaded methods.

The following line of code calls Main's constructor, which doesn't accept any method argument:

Main print = new Main(); 
public class Main {
  public Main() {
    this(7);/*from  w ww.ja v  a  2 s  .co m*/
    System.out.println("public");
  }

  private Main(int val) {
    this("Sunday");
    System.out.println("private");
  }

  protected Main(String val) {
    System.out.println("protected");
  }

  public static void main(String[] args) {
    Main print = new Main();
  }
}