简体   繁体   中英

Java , method calling from two objects of a class. One object in the same class and one object in other class

I am having this code in which I have created an object of class namely MyClass in it. I have created an object inside main method. I want to call the method of class but it gives StackovetrflowError at run time. Suggest me the way to overcome the error.

here is the code...

class MyClass {


  public MyClass obj2  =new MyClass();


    public void show()
    {
        System.out.println("in show method...");
    }

    void message()
    {
        System.out.println("in message method...");
    }
}


public class AccessDemo {

    public static void main(String[] args) {

         MyClass obj1  = new MyClass();

            obj1.obj2.show();
    }
}

I want to get the message printed inside the methods namely show() and message() .

You've got needless recursion going on here:

class MyClass {

    public MyClass obj2 =new MyClass();

Why are you creating a MyClass instance inside of MyClass? This will repeat endlessly and recursively until you run out of memory.

Solution: don't do this. Get rid of the obj2 variable as it serves no purpose other than to make your program fail. Instead simply call your methods on the obj1 variable created in the main method.

as Hovercraft Full Of Eels described the problem is with : public MyClass obj2 =new MyClass(); but also you can have only public MyClass obj2; and not initialize it in the class scope, instead of it initialize it where it is needed, example:

class MyClass {

public MyClass obj2;

public void show()
{
    System.out.println("in show method...");
}

void message()
{
    System.out.println("in message method...");
}
//initializze it here
public void someVoid(){
   //you may do something else
   obj2=new MyClass();
}
} 

and now you can have:

public class AccessDemo {

public static void main(String[] args) {

     MyClass obj1  = new MyClass();

        obj1.someVoid();
        //now this should work properly
        obj1.obj2.show();
}
}

Output:

in show method...

obj1.obj2.show();

is incorrect. Instead you simply need to go:

obj1.show();
obj1.mesage();

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