Examveda
Examveda

what is the result of the following piece of code:
public class Person{
        public void talk(){
                System.out.print("I am a Person");
        }
}

public class Student extends Person{
        public void talk(){
                System.out.print("I am a Student");
        }
}

public class Test{
        public static void main(String args[]){
                Person p = new Student();
                p.talk();
        }
}

A. I am a Person

B. I am a Student

C. I am a Person I am a Student

D. I am a Student I am a Person

Answer: Option B


This Question Belongs to Java Program >> Overriding And Overloading

Join The Discussion

Comments ( 2 )

  1. Mahesh MR
    Mahesh MR :
    7 years ago

    p is holding the Student class object, hence when the method p.talk() is called the Student class method is accessed.

  2. Shrey Soni
    Shrey Soni :
    7 years ago

    Even though child class has access to parent's method, it prefer its own method when method is called. This is due to method overriding.
    Child's method is overriding where parent's method is overridden.

Related Questions on Overriding and Overloading