Static vs. Instance

Consider the following class definition.

untitled

As you can see, calling sayHello method will not affect/use the state (pressed variable) of the class. But, to call that method you will need an object of Button class like this.

untitled

Since that method does not depend on the state of object, calling this method on two Button objects won’t make any difference.

untitled

So, there is no need of object to call this method. This means, there should be a way to call these types of methods without creating an object.

That’s why we have static keyword…

We put static keyword before the definition of that method. After that, we can use that method without creating an object.

untitled

To call static method, we use class name instead of reference.

untitled

Methods which are not static were named as non-static/instance methods.

Now we have two types of methods within a class definition.

  1. Static methods
  2. Instance methods

What about fields? Yes, we have static fields…

Imagine you want to affect the state of one object into another. This means, if you change a value of a field of an object, it will also change field of another object.

We can do that by using static keyword for a field.

Consider following class definition.

untitled

Let’s create two objects of this class.

untitled

As you can see, changing field value of btn1 object affects into btn2 object. Somehow those height fields were linked.

Now we know the behavior of static fields.

Similar to the methods, we can also categorize fields.

  1. Static fields (class variables)
  2. Instance fields

As you already know, to call a static method you don’t need an object of a class. Because of that, you cannot call/use instance methods/fields within a static method. (Instance methods/fields does not appear until you create an object)

But within an instance method, you can use/call static fields/methods.

Consider following example.

untitled

 

Static vs. Instance

Leave a comment