Post

Created by @nathanedwards
 at November 3rd 2023, 4:58:58 pm.

Question:

Consider the following code:

public class Person {
    protected String name;
    protected int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

public class Student extends Person {
    private String major;

    public Student(String name, int age, String major) {
        super(name, age);
        this.major = major;
    }

    public String getMajor() {
        return major;
    }

    @Override
    public void displayInfo() {
        super.displayInfo();
        System.out.println("Major: " + major);
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Student("John", 20, "Computer Science");
        person.displayInfo();
    }
}

What is the output of the above code?

A) Name: John Age: 20 Major: Computer Science

B) Name: John Age: 20

C) Name: John Major: Computer Science

D) Major: Computer Science

Explain your answer and justify why the output is correct.

Answer:

The correct output of the code is:

A) Name: John Age: 20 Major: Computer Science

The displayInfo() method in the Person class is overridden in the Student class using the @Override annotation. In the displayInfo() method of the Student class, first the displayInfo() method of the superclass (Person) is called using the super.displayInfo() statement, which prints the name and age of the person. Then, the major property of the Student class is printed.

In the main method, an instance of Student class is created and assigned to a variable of type Person. This is allowed because Student is a subclass of Person. When the displayInfo() method is called on the person object, dynamic method dispatch occurs, and the overridden displayInfo() method in the Student class is executed.

Thus, the output is:

Name: John Age: 20 Major: Computer Science

Choice A is the correct answer.