Ashish kumar
Ashish kumar

Reputation: 21

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().

Upvotes: 1

Views: 1954

Answers (3)

void
void

Reputation: 7890

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...

Upvotes: 1

jnd
jnd

Reputation: 754

obj1.obj2.show();

is incorrect. Instead you simply need to go:

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

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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.

Upvotes: 6

Related Questions