In a class, I have 2 methods. In method1 I created an object, but I can't use the same object in method2.
Why? Please help with a simple example.
The coding is too big, so I have given the layout
public class Sub
{
}
public class DataLoader
{
public void process1()
{
Sub obj = new Sub();
}
public void process2()
{
// here I can't use the object
}
}
You should use member variables in your class.
Read up on different variable scopes (specifically, instance variables in this case). You can also pass your object as a parameter, like codesparkle mentioned in their answer.
You have to set the object as a class field, then you can access it from every method of your class.
The short answer (without seeing your code) is that the object created in
Method1
doesn't have any visibility, or scope, inMethod2
.There are already some good answers here that show you how to solve your specific problem. But the real answer here is to familiarize yourself generally with the concept of Scope. It's a fundamental part of programming and learning more about it will help you tons.
There are many good articles and videos on the subject. This video is a great start. Good luck!
The reason why this isn't working is scope. A local variable can only be accessed from the block it is declared in. To access it from multiple methods, add a field or pass it to the other method as a parameter.
Field:
Parameter: