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 Meet Objects Creating Classes

Akhil Matabudul
Akhil Matabudul
2,386 Points

Accessing non-static variables in MAIN?

From the video i wrote exactly the same thing as he did but when I ran the main I got an error saying that can't access the characterName since its not a static variable. I have some limited prior knowledge of java to know that static methods can't really access static variables per say, but my question is how come he didn't get an error in the video like I did?

2 Answers

michaelcodes
michaelcodes
5,604 Points

Saraj Singh did a very good job explaining the difference here. I just want to add to that and demonstrate the difference in code. Say you have a class named Car that has both static and non-static vars\methods. To call a static method from this you would use:

Car.driveFast();

For the non-static you must first create an instance then use the method:

Car dodge = new Car();
dodge.setSpeed();

Ok, since you mentioned that you have limited Java knowledge, I am going to give you some gyan (knowledge ). If let's understand difference between static and non static fields. Static: also known as class fields,the ones which are available without any object and comes into existence once related class is loaded. There's only one copy of them. E.g. main method in main class. We declare it static because JVM don't create object of this main class and simply will be able to call this method.

Non static: they come into existence once you create a object of class.

Now think this way while writing code, that variable or method you are trying to access is part of object or class and will they be available during runtime while executing your piece of code? In this particular case you are trying to access something which will be only available if you declare object of class and then use that to access variable or make field static, make it always available. I suggest try both ways and you will appreciate the difference.