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();
}
}
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
Join The Discussion
Comments ( 2 )
What is method overriding in Java?
A. Redefining a superclass method in a subclass
B. Defining a new method with the same name in a subclass
C. Making a method private in a subclass
D. Hiding methods in a superclass
What is the purpose of method overloading in Java?
A. Creating static methods
B. Hiding methods in a superclass
C. Redefining methods in a subclass
D. Defining multiple methods with the same name but different parameters
A. @OverrideMethod
B. @OverrideSuper
C. @Override
D. @OverrideParent
What happens when a subclass tries to override a final method from the superclass in Java?
A. The final method is hidden
B. It results in a compilation error
C. The final method becomes static
D. The final method is hidden
p is holding the Student class object, hence when the method p.talk() is called the Student class method is accessed.
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.