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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With