Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object initialized in the main class and using the same object in a method/function for different purpose?

Tags:

java

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.

like image 384
SYED SAAD ALI Avatar asked Aug 08 '26 18:08

SYED SAAD ALI


1 Answers

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.

like image 199
arshajii Avatar answered Aug 10 '26 07:08

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!