101k views
0 votes
Given the following code, find the compile error.

public class Test{
public static void main(String[] args){
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Person x){
System.out.println(x.toString());
}
}
class GraduateStudent extends Student {
public String toString(){ return "GraduateStudent";}
}
class Student extends Person{
public String toString(){ return "Student";}
}
class Person extends Object{
public String toString(){ return "Person";}
}
a. m(new Object()) causes an error
b. m(new Person()) causes an error
c. m(new Student()) causes an error
d. m(new GraduateStudent()) causes an error

User Ropeney
by
4.1k points

1 Answer

6 votes

Answer:

a. Object cannot be converted to Person

Step-by-step explanation:

This program demonstrates polymorphism.

e.g., a Student IS a Person therefore you can call m() with a Student as well as a Person object.

The same goes for GraduateStudent.

However, and Object is not a Person, so the last call fails. This can be deducted by the type checking that happens at compile time.

User Volodymyr Usarskyy
by
4.7k points