简体   繁体   中英

java.lang.StackOverflowError while calling a method

I am learning interface behavior. i have created a interface and its implementer class, while calling method m1() i got java.lang.StackOverflowError. i dont know why. can anybody tell me proper reason behind this !!!!!! Here is the code :

public interface Employee {
     String name="Kavi Temre";
}

public class Kavi implements Employee{
    Employee e= new Kavi();
    public static void main(String[] args) {

        Kavi kt=new Kavi();
        kt.m1();
    }

    void m1()
    {
        System.out.println(Employee.name);
        //System.out.println(e.name);
    }
}

both sysout give the same error : please tell me what is actually going on here ??

Console output:

Exception in thread "main" java.lang.StackOverflowError
    at Kavi.<init>(Kavi.java:2)
    at Kavi.<init>(Kavi.java:2)
    at Kavi.<init>(Kavi.java:2)
    at Kavi.<init>(Kavi.java:2)
    at Kavi.<init>(Kavi.java:2)
    at Kavi.<init>(Kavi.java:2)
    at Kavi.<init>(Kavi.java:2)
    .....

When you call

Kavi kt=new Kavi();

it initializes the e member :

Employee e = new Kavi();

which then initializes its own e member, which gives you an infinite chain of calls to the Kavi constructor. Hence the StackOverflowError.

It's equivalent to :

Employee e;
public Kavi ()
{
    e = new Kavi();
}

A constructor shouldn't call itself in an infinite loop.

Removing the Employee e = new Kavi() line will solve your issue. If your class must hold a reference to an Employee , consider passing it to the constructor :

public Kavi ()
{
    this.e = null;
}

public Kavi (Employee e)
{
    this.e = e;
}

public static void main(String[] args) {

    Employee e = new Kavi ();
    Kavi kt=new Kavi(e);
    ...
}

An alternative solution is to change :

Employee e = new Kavi();

to

static Employee e = new Kavi();

That would be a valid solution if all instances of Kavi share the same Employee instance referred by e .

Inside your class Kavi you are declaring a field e of type Employee and initialize it with a new Kavi object.

When creating the first instance of the class Kavi you are triggering the aforementioned initialization and create a new Kavi object (line 2) that also creates a new Kavi and so on and so on. So the problematic line is

Employee e= new Kavi();

After a good number of Kavi objects have been created, the stack will reach its limit and the exception will be thrown.

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