Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Harnessing the Power of Objects Constants

Andre Kucharzyk
Andre Kucharzyk
4,479 Points

Public variable cannot be accessed. Why?

So I wanted to experiment and fully understand the reason behind creating static variable... I wanted to see what will happen if I declare public int and call it from a Main.class. So i've created an instance of PezDispenser class in my Main class and called PezDispenser.MAX_PEZ. Compiler gives me an error: "Error:(12, 40) java: non-static variable MAX_PEZ cannot be referenced from a static context". Why?

Main.java
package com.company;

public class Main {

    public static void main(String[] args) {

        PezDispenser pez = new PezDispenser("Andre");
        System.out.println(PezDispenser.MAX_PEZ);

    }
}

PezDispenser.java
package com.company;

class PezDispenser {
    public int MAX_PEZ = 12;

    final private String characterName;

    public PezDispenser(String characterName) {
        this.characterName = characterName;
    }

    public String getCharacterName() {
        return characterName;
    }

}

3 Answers

Hi there,

Your code is trying to access MAX_PEZ from the class, not from an instance of the class. That behaviour requires a static variable/constant.

Steve.

Andre Kucharzyk
Andre Kucharzyk
4,479 Points

Can I access public int MAX_PEZ = 12; from the main class somehow while not making it static?

If answer is "no" why there is an option to create public variable?

The answer is 'No'. The public access is granted for instances of the class - the instance variables don't exist, so can't be accessed, unless they have class-level rights, granted by static. That's my understanding of the situation but I may not have used the correct technical words.

Steve.

Andre Kucharzyk
Andre Kucharzyk
4,479 Points

Well, I have found a way to access such a public variable. When you call it from the main class just have to prefix it with name of the instance of that variables class.

One for Craig Dennis to explain, I reckon!

Craig Dennis
Craig Dennis
Treehouse Teacher

Hi Andre!

Not sure I follow can you show me?

Thanks!

Andre Kucharzyk
Andre Kucharzyk
4,479 Points

Hi Craig, thanks for answering.

Basically, I forgot how to call a public (non static) variable from another class, and that's why I posted this thread. Sorry for the problem.