简体   繁体   中英

parent child class StackOverflowError exception

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:

@Override
public String getName(){
    return "Child Class Name is: " + super.getName();
}

Your objpeople2.getName() is accessing the getName() of the current class, which causes calling the same method recursively that's way StackOverFlorError Exception was thrown. Use super keyword to refer to the super class of the current class.

In you child class, you are calling getName() method recursively, which causes out of memory, hence StackOverflowException.

Try to call like bellow.

@Override
public String getName(){
    return "Child Class Name is: " + name;
}
@Override
public String getName() 
{   
 return  "Child Class Name is: "+ getName();
}

In this method getName() calling as recursive call. Hence it never ends the calling of same method its giving StackOverflowException

Changed it as Below.Its working Now

@Override
public String getName() 
{   
 return  "Child Class Name is: "+ super.Name;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM