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 trialAndre Kucharzyk
4,479 PointsPublic 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?
package com.company;
public class Main {
public static void main(String[] args) {
PezDispenser pez = new PezDispenser("Andre");
System.out.println(PezDispenser.MAX_PEZ);
}
}
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
Steve Hunter
57,712 PointsHi 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
4,479 PointsWell, 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.
Steve Hunter
57,712 PointsOne for Craig Dennis to explain, I reckon!
Craig Dennis
Treehouse TeacherHi Andre!
Not sure I follow can you show me?
Thanks!
Andre Kucharzyk
4,479 PointsHi 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.
Andre Kucharzyk
4,479 PointsAndre Kucharzyk
4,479 PointsCan 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?
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsThe 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 bystatic
. That's my understanding of the situation but I may not have used the correct technical words.Steve.