Functions

Imagine you need to write a program which reads birth day from a user & print his age. You may write something like this:

untitled

Suppose now you need to read another user birth day & print his age.

You may write something like this:

untitled

And later you found something wrong with blah blah code section. So you will correct it. Since you have used same code twice, you will need to fix that error twice. If you have used ten times that code, you’ll have to fix that error ten times. That is so much waste of time. That’s why we have functions.

Functions/Procedures allow us to use same calculation for different values.

So, if we have used blah blah code section within a function, we don’t need to fix the same code multiple times.

When we declare a function, first we need to specify the return type. Return type specifies the type of output value of that function. For example: If we return a number, return type is int.

Then we need to specify the name of that function. After that we specify parameter/argument list of that function. Each parameter is separated by a comma.

Here is an example:

untitled

This is how we use that function within our program:

untitled

As you can see, Instead of using blah blah code again & again, we call CalculateAge function. This simplifies our code & improves reusability. Also other programmers can use that function without thinking about its implementation (blah blah code section). So, they can focus on their own coding problems instead of thinking about blah blah code section.

(Also you can declare variables inside of the function. We called them as local variables.)

Advertisements
Functions

Recursion

What if you call a function within itself? Well, that will make an infinite loop unless you make a break condition. Such behavior can be use to create another kind of loop called recursion.

Here is an example:

untitled

If you call the factorial function with number 4 as a parameter:

factorial ( 4 )                                     factorial ( 4 ) will expands to 4 * factorial ( 4 – 1 )

4 * factorial ( 4 – 1 )                        factorial ( 4 – 1 ) will expands to 3 * factorial ( 3 – 1 )

4 * 3 * factorial ( 3 – 1 )                  factorial ( 3 – 1 ) will expands to 2 * factorial ( 2 – 1 )

4 * 3 * 2 * factorial ( 2 – 1)            factorial ( 2 – 1 ) will expands to 1 (break condition)

4 * 3 * 2 * 1

Final value is 4 * 3 * 2 * 1 which is 24.

Same behavior can be created using a loop:

untitled

Note: Thinking in recursion instead of loops will expand your brain. But it will break your stack at some point!

Recursion

Classes & Objects

Suppose you want to make a function which holds some kind of state.

For example:

untitled

If you call buttonPressed function once it will print “on”. If you call it again it will print “off”. As you can see this function holds/manage some kind of state. In other words, its behavior is influenced by its history. The output of this function is depends on previous call of this function. Also we can say output of this function is depends on the time we call this function. Well… now our code feels the time… hmm… (There is no concept of time without history)

Imagine above code used to handle button press event of a window & now you want to add another button. As you can see you cannot use the same function to handle new button press event. So you will have to add another function & global variable for that new button.

Now our code will be something like this:

untitled

That’s ok for two buttons. But what if we want to handle 10 buttons?

So there should be some kind of way to use first example code as a template to create others. In other words, once we define global variable & function, there should be a way to create copies of it. In that case, we don’t need to create one global variable & function per button.

To use first code example as a template, we put it into a class.

untitled

Then we can use that class to create copies of it. Each copy of this class is named as object/instance of that class. The process of creating new object is named as instantiation.

The state of one object does not affect the other. They are independent. So if you change the state of one object, it will not impact on others.

If you look at the class definition code, we have named our class as Button. By declaring a class, we also introduce a new type into our programming language. We can define variables using this new type. We named those variables as references.

In this code, x is a variable and y is a reference.

untitled

Important: variable holds a value and reference holds an object.

To create a new object of class, we use new command with class name.

untitled

To capture the created object, we use a reference.

untitled

Now reference y holds an object of Button class. Let’s create another object of that class.

untitled

Now y and z holds two different objects whose type is same. Changing state of y does not affect the state of z.

The content of the class is named as members. As you can see there are two types of things we can put into a class. They are variables & functions. If we put variable into a class, we named it as a Field. If we put a function into a class, we named it as a Method.

According to the Button class definition, buttonPressed is a method & state is a field.

To access members of an object, we use the dot character.

untitled

Calling a method of an object is also called Invoking a method. When we consider class internals, method invocation of an object accomplish by sending a message into that object.

Let’s move into our Button example. Since we have a class, we don’t need to create one global variable & function per button. Instead, we create one reference & object per button. That’s easy…

untitled

 

Classes & Objects

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

Constructor

Imagine you want to do something automatically when an object was created. Assign values to fields, call other functions etc…

To do that, we have a special method called constructor. It does not have a return type & its name is same as class name.

untitled

Now if we create an object of Button class…

untitled

The main use of constructor is to initialize the state of an object.

Constructor

Encapsulation

Consider the following class definition.

untitled

Imagine someone assigned invalid value to age field.

untitled

As you can see, we need a way to avoid such type of data corruption. We need a way to hide data variables (fields) from outside world. We need to filter invalid data insertion.

That’s why we need access modifiers.

Access modifiers control how outside world access our class members.

Let’s consider private access modifier:

If you put private keyword in front of a class member, that member will be only accessible to class itself. (Outside world cannot use it)

For example:

untitled

untitled

Now we can block direct access to our data members by outside.

So, if outside world wants to change the value of age field, how to do it?

Simple, we provide methods… we called them getters/setters

untitled

setAge method can be use to change the value of age field. getAge method can be use to read the value of age field.

untitled

As you can see, still outside world can give invalid values to age field.

All we need to do is, add a condition into setAge method to filter invalid values.

untitled

Well, that works!

All we did was data hiding & providing getters and setters to access our data. This is what we called as Encapsulation.

Encapsulation allows us to avoid data corruption.

Following image clearly illustrates this concept. Data is tightly covered by the code. The only way to access the data is using the code within that object.

untitled

Encapsulation also defines has a relationship.

If you consider the definition of Student class, you will see that Student has age… If Student class has a field called name, we can say Student has name

Encapsulation

this keyword

Consider following code:

untitled

What if we rename the val parameter as age? (We need to use meaningful names for parameters)

untitled

At this point within setAge method, field age was shadowed by parameter age. Now we need a way to distinguish those two variables.

That’s why we have this keyword.

this keyword always refer the current object. (Object reference which refers to the instance the current method was called on)

untitled

Let’s consider another usage:

untitled

Since this keyword always refers the current object, you cannot use it within static method. ( static method can be called without creating an object)

untitled

 

this keyword