简体   繁体   English

父子类StackOverflowError异常

[英]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. 第一个getName方法工作正常。当我尝试使用第二个时,它生成异常。

objpeople2.getName() is generating java.lang.StackOverflowError exception objpeople2.getName()正在生成java.lang.StackOverflowError异常

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. 你的objpeople2.getName()正在访问当前类的getName() ,这会导致以递归方式调用相同的方法,这就是抛出StackOverFlorError Exception的方式。 Use super keyword to refer to the super class of the current class. 使用super关键字来引用当前类的超类。

In you child class, you are calling getName() method recursively, which causes out of memory, hence StackOverflowException. 在您的子类中,您以递归方式调用getName()方法,这会导致内存不足,从而导致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. 在此方法中,getName()调用为递归调用。 Hence it never ends the calling of same method its giving StackOverflowException 因此,它永远不会结束调用给出StackOverflowException的相同方法

Changed it as Below.Its working Now 将其更改为Below.Its立即工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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