0

How do I reference an object created outside of the main method, within the main method. An example being below. Lets pretend all the other code is correct and the Apple class is complete. I would just like to know how to be able to reference apple1 in the main method when it is created outside. I understand I "cannot reference the non-static variable from a static context".

What's the work around?

public class Fruits {

    private Apple apple1 = new Apple();

    public static void main(String[] args) {

        System.out.println("The colour of the apple is "apple1.getColour());

    }
}

Hopefully this question makes sense to someone. Thanks in advance.

EDIT: I don't want to change apple1 to static.

Jamie
  • 3
  • 5

2 Answers2

2

Make apple1 static to be accessible by main.

private static Apple apple1 = new Apple();

Or make a Fruits object, and access it through that.

dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
1

Your apple1 is an instance variable (aka "instance field"). It doesn't exist until/unless you create an instance of Fruits, e.g. via new. main is a class method, not an instance method, so it doesn't automatically have an instance to work with.

So you could do:

Fruits f = new Fruits();
System.out.println(f.apple1.getColour());

...in main to access it.

Alternate, make it static so it's a class variable (or "class field"), as Chandler notes:

private static Apple apple1 = new Apple();

Then it's accessible from a class method like main:

System.out.println(apple1.getColour());
// or
System.out.println(Fruits.apple1.getColour());
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    This was really helpful. People may be answering the question but they need to answer it in a way that is noob friednly. Yours was. Thanks! – Jamie May 18 '17 at 14:43