interface - java.lang.StackOverflowError while calling a method -
i learning interface behavior. have created interface , implementer class, while calling method m1() got java.lang.stackoverflowerror. dont know why. can tell me proper reason behind !!!!!! here 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 same error : please tell me going on here ??
console output:
exception in thread "main" java.lang.stackoverflowerror @ kavi.<init>(kavi.java:2) @ kavi.<init>(kavi.java:2) @ kavi.<init>(kavi.java:2) @ kavi.<init>(kavi.java:2) @ kavi.<init>(kavi.java:2) @ kavi.<init>(kavi.java:2) @ kavi.<init>(kavi.java:2) .....
when call
kavi kt=new kavi(); it initializes e member :
employee e = new kavi(); which initializes own e member, gives infinite chain of calls kavi constructor. hence stackoverflowerror.
it's equivalent :
employee e; public kavi () { e = new kavi(); } a constructor shouldn't call in infinite loop.
removing employee e = new kavi() line solve issue. if class must hold reference employee, consider passing 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 change :
employee e = new kavi(); to
static employee e = new kavi(); that valid solution if instances of kavi share same employee instance referred e.
Comments
Post a Comment