Issue
I have a class that contains the following coding
import java.util.Scanner;
import java.io.*;
public class someClass {
public static void main(String[] args) {
Product[] p= new Product[3];
p[0] = new Product();
p[1] = new Product();
p[2] = new Product();
p[0].name="John"; // Product is a class which contains variable String name;
// and a method getName() which is returning the name;
p[1].name="Tony";
p[2].name="Abraham";
somePrintMethod();
}
public static void somePrintMethod() {
for(int i =0;i<3;i++) {
System.out.println(p[i].getName());
}
}
}
So my question is can I use the object defined in the main class in any other method for other
purpose in the same class or there is any method to use that object because I am trying to
do that and it is giving me an error and I cannot figure out how to do it.
Solution
You can make p
a static
variable, declared outside of main
:
static Product[] p = new Product[3];
But you should of course first ensure that doing something like that makes sense in the context of your program.
Answered By - arshajii
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.