OCA Java SE 8 Mock Exam - OCA Mock Question 29








Question

What is the output of the following code?

class Person {
  protected int age;

  protected void setAge(int val) {
    age = val;
  }

  protected int getAge() {
    return age;
  }
}

class Professor extends Person {
  Professor(String val) {
    specialization = val;
  }

  String specialization;

  String getSpecialization() {
    return specialization;
  }
}

public class Main {
  public static void main(String args[]) {
    Professor s1 = new Professor("AAA");
    Professor s2 = new Professor("BBB");
    s1.age = 45;
    System.out.println(s1.age + s2.getSpecialization());
    System.out.println(s2.age + s1.getSpecialization());
  }
}

                a 45BBB 
                  0AAA 

                b 45AAA 
                  0BBB 

                c 45AAA 
                  45BBB 

                d 45BBB 
                  45BBB 

                e Class fails to compile. 




Answer



A

Note

The constructor of the class Professor assigns the values "AAA" and "BBB" to the variable specialization of objects s1 and s2.

The variable age is protected in the class Person.

Also, the class Professor extends the class Person.

Hence, the variable age is accessible to reference variables s1 and s2.

The code assigns a value of 45 to the member variable age of reference variable s1.

The variable age of reference variable s2 is initialized to the default value of an int, which is 0.

class Person {//  www . j a va2s.  com
  protected int age;

  protected void setAge(int val) {
    age = val;
  }

  protected int getAge() {
    return age;
  }
}

class Professor extends Person {
  Professor(String val) {
    specialization = val;
  }

  String specialization;

  String getSpecialization() {
    return specialization;
  }
}

public class Main {
  public static void main(String args[]) {
    Professor s1 = new Professor("AAA");
    Professor s2 = new Professor("BBB");
    s1.age = 45;
    System.out.println(s1.age + s2.getSpecialization());
    System.out.println(s2.age + s1.getSpecialization());
  }
}

The code above generates the following result.