I have Two Class in school package
Class school
package school;
public class people
{
String Name = null;
public String getName()
{
return "Super Class Name : " + Name;
}
public void setName(String name)
{
Name = name;
}
}
Class Students
package school;
public class students extends people
{
public static void main(String[] args)
{
people objpeople1 = new people();
people objpeople2 = new students();
objpeople1.setName("David");
objpeople2.setName("Davis");
System.out.println(objpeople1.getName());
System.out.println(objpeople2.getName());
}
@Override
public String getName()
{
return "Child Class Name is: "+ getName();
}
}
The first getName method is working fine.When I tried to use the second one its generating exception.
objpeople2.getName() is generating java.lang.StackOverflowError exception
Try this:
Your
objpeople2.getName()is accessing thegetName()of the current class, which causes calling the same method recursively that’s way StackOverFlorError Exception was thrown. Usesuperkeyword to refer to the super class of the current class.