Help me understand when to use static on functions/methods
My teacher is trying to explain this but it really makes no sense the way he is explaining it. If I understand from my own research only, static attached to a method means that it can be called without referencing it with an object. IE: (this code isn't correct just want to do something general)
Code :
Main function {
int i = area(); // This one would work
int t = length(); // This wouldn't work unless accessed by an object?
Object object = new Object;
object.area(); // Wouldn't work?
object.length() // Only way the length function could be run?
}
static int area function {
blah blah
return k;
}
int length function {
blah blah;
return k;
}
Hopefully this makes sense. Basically I want to know what the static keyword does. And sorry if they aren't supposed to be called functions, I mean methods. I came from C, and this class is an introduction to object oriented design so its still new to me. Any good sites to learn object oriented design for Java from because my teacher is not the greatest? Thank you!
Re: Help me understand when to use static on functions/methods
Re: Help me understand when to use static on functions/methods
You're about right. Marking something with 'static' allows it to be accessed any code that has access to the class (usually obtained in code by naming the Class itself - such as "System.out"). The best (most authoritative) place to learn Java on your own is from the Sun (now Oracle) docs. The relevant page for 'static':
Understanding Instance and Class Members (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
Always remember what The Jade Warlord says in The Forbidden Kingdom:
Quote:
The man who honors his teacher honors himself
Forbidden Kingdom 8 of 10 - YouTube
Re: Help me understand when to use static on functions/methods
Static in Java means it all related to class , nothing at instance level.
1) static method or field can be accessed by using Class name and that's the recommended way.
2) non static field can not be accessed inside static context.