4

Static Variables and Methods (Java)

 3 years ago
source link: https://dev.to/mobolanleadebesin/static-variables-and-methods-java-1bcl
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Static Variables and Methods (Java)

Jul 2

・2 min read

Variables

Static variables are tied to the Class itself. Each object of a class shares the static variable.

Non-static variable (instance variables) are tied to the object. In the example below, every object of the Cat class has its own name variable. However, every object shares the catCount variable.

When you see the static keyword in front of a variable name think of a shared variable.

Class Cat 
{
String name; // Non-static variable (each object has it's own copy) 
static int catCount; //Static variable (each object of the class Cat shares this variable

Cat(String name){
this.name = name; // Non-static variables can be referenced with "this" keyword 
Cat.catCount++; // Static variables are referenced using the class name 
}
Enter fullscreen modeExit fullscreen mode

Methods

Java methods are divided into two categories. Instance methods and Static methods.

Instance Methods

These methods are called on an object and they have access to an objects data (non-static variables). This makes sense. Since an object is an instance of a class, an instance method works on objects.

The reason that instance methods are able to access an objects data is because they have a reference to the object. That reference is stored in the keyword "this". "this" holds a reference that tells us where the object we are referencing is. Without "this" we can't refer to the object.

When you call an instance method, the object that you called the method on is actually passed along to that method as the first argument, we just don't see it.
What we see:

Cat sally = new Cat(); 
String name = sally.getName(); 
Enter fullscreen modeExit fullscreen mode

What is actually happening:

Cat sally = new Cat(); 
String name = Cat.getName(sally); 
Enter fullscreen modeExit fullscreen mode

The object sally is being passed into the getName method. Then inside the method, the object sally will be referred to as "this".

Static Methods

These methods do not have access to an objects data. Since they don't have an object reference. Static methods don't have "this". Instead a null value is passed to static methods. But, static methods can reference the static variables of the class and other static methods.

Static methods allow us to call a method before we create any objects because they are tied to the class not the object. This is how the main() method works for example.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK