Classes & Subclasses | Class Relationships

Back To Class

I will be going back to classes again after taking a short break from it. I will be continuing from the previous lesson on classes so pls do refer to it if you are lost or you have not read it before. The post can be found here. Today I will be writing more on the relationships between the classes and how it can be used to take your programming into another level. Besides calling it class and subclass , the relationship also often called parent and child class , just a FYI in case you are wondering what is the different between those two names.

Class Examples

Lets go back to the Bicycle class we looked at previously and then we look into a subclass of it.

public class Bicycle {

    // the Bicycle class has three fields
    public int cadence;
    public int gear;
    public int speed;

    // the Bicycle class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }

    // the Bicycle class has four methods
    public void setCadence(int newValue) {
        cadence = newValue;
    }

    public void setGear(int newValue) {
        gear = newValue;
    }

    public void applyBrake(int decrement) {
        speed -= decrement;
    }

    public void speedUp(int increment) {
        speed += increment;
    }

}

And the subclass or the child class ,

public class MountainBike extends Bicycle {

    // the MountainBike subclass has one field
    public int seatHeight;

    // the MountainBike subclass has one constructor
    public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {
        super(startCadence, startSpeed, startGear);
        seatHeight = startHeight;
    }	

    // the MountainBike subclass has one method
    public void setHeight(int newValue) {
        seatHeight = newValue;
    }	

}

In order to fully understand the class relationships , we must understand one of the main OOP concepts , called “inheritance”. Of course we all know what is the meaning of the word inheritance but we must now look at it from the view of an OOP programmer. Suppose there is a father and a child , in our imaginary land , flying kite. The father is sitting beneath a pine tree and the child is running with the kite. What can we say about the relationship? Here are a few things ,

  1. Both have similar physical and non-physical attributes , such as arms , legs , eyes , names , address , etc ..
  2. Both have similar similar capabilities , such as reading , running , talking , laughing and so on
  3. But the child has a kite while the father does not have any

So for those which are similar between the father and child , we can say that the child has inherited from the father. Of course father is a human so we can say all human belong to a one distinct class called a “person” class. But for attributes or capabilities , functions , that the child has but the father doesn’t , maybe playing computer games , then we can associate it with the child and child alone.

If you were to examine closely at the MountainBike Class which “extends” or inherits from the Bicycle class ,it has a new attribute and a new method associated with the attribute, which are not available to its parent class. Therefore , if you are to create a new bicycle , you could never set its seatHeight to any value because it doesn’t exist for a normal Bicycle. Only a MountainBike would have the ability to adjust its seatHeight.

And if you look at the constructor of the MountainBike , you would see the word “super” before “startCadence” , “startSpeed” and “startGear” , which is saying that those are the same the parents. The only new value set would be the “startHeight”.

Class Relationships Conclusion

I hope you have a much clearer idea of class relationships and inheritance after reading. Hope to see you again!..

Programming | Loops | If-Else

Introduction On Programming If-Else & Loops

Thats right. I forgot , again , to go through the simple matter of loops and if-else so I am going to have to touch up on these topics before we go any further into classes. This will be short I promise. There isn’t much to say about this. Once you read the codes below , you will be able to understand it without even reading my explanation.

Here is one example of if-else that we have actually looked at before previously ,

public int setGear(int newValue) {
       if ( newValue <= 24 ) {
       gear = newValue;
       return 0;
       }
       else {
        return 1;
        }
}

I think it is self-explanatory and if it is not for you , pls do refer to my previous post where I had gone through the code. There is one thing about if-else that I didn't go over in the last post however and that is about the scope. If the code after "if" is only 1 sentence , there is no need to place the curly braces "{ }" to wrap the code , it is understood that the statement would be executed if the condition is true.

public int setGear(int newValue)
{
       if ( newValue <= 24 )
       gear = newValue;
              else
        return 1;
}

So if the newValue is less than or equal to ( <= ) 24 , the following statement would be executed and if it were not , then the statement following else statement would be executed. Suppose you wish to have more than 1 if and else. Say you would like the code to change depending whether the value is less than 10 or less than 20 or less than 30. In this situation , you could either go through if-else nests or you would use elseif.

            if (Condition_1)
{
    // Statement_1;
}
else if (Condition_2)
{
    // Statement_2;
}
else if (Condition_3)
{
    // Statement_3;
}
else
{
    // Statement_n;
}

As you can see , the only change is that it has multitude of ifs and only one else at the bottom. There are a few more conditional branching methods but they fall along the if-else line of thinking so you shouldn't have much difficult time with them once you get familiar with using if-else.

Loops

Now for something thats much more enjoyable than if-else , that is looping. Basically you want something to be repeated over and over again till a certain condition is met. The simplest is a for loop. Here is how it looks like in Java ,

for (int i = 1; i< 10 ; i++)  {
    System.out.println(i);
}

We defined a variable called "i" which is of an integer type and it has no life outside of the for loop. A temporary variable if you will. Then we assigned it to value of 1 , and next statement separated by ";" says till it is less than 10 , which means until it is 10 before it goes over to loop statement , "i++". Here "++" means increment by 1 , same as i+1 . so 1++ = 2 , 2++ = 3 and so on. And then of course , it will be looped. This is what it looks like if you were to do it manually. Oh and "System.out.println" does the same thing as "System.Console.Writeln".

System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
System.out.println(6);
System.out.println(7);
System.out.println(8);
System.out.println(9);

Copy and paste 9 lines is no big deal but if you were to do the same for thousands of lines manipulating millions of values and you begin to see the power of loops which allows you to do the same in a few lines. Here is a more advanced example of a loop ,

for (int i = 1,  j = 100;  i < 100;  i = i+1, j = j-1)  {
    System.out.println(i + j);
}

So "i" is assigned the value of 1 and increment by 1 and "j" is assigned 100 and decrement by 1. The loop will then stops when "i" reaches 100. Take note that in the end , "i" will reach 100 and the loop will ends but not at when it reaches 99. So it would prints out ,

System.out.println(1 + 100);
System.out.println(2 + 99);
.
.
.
.
.
.
.
.
System.out.println(100 + 1); // then no more because 100 is not less than 100 and condition fails.

Again , there are other types of loops such as while loop and do while loops. But I think for now this will suffice. I hope you has a great time just as I did.

Access Levels In OOP | Access Levels

Intro To Access Levels

As I said yesterday in the post on classes , I would be going over the meaning of “Public” , “Private” , “Protected” which are either called access levels or access modifiers or whatever it is called when you read this post. Their main purpose to specify how they can be used by other objects during execution. They are used when we define a variable or a method , such as

public int gear;
.
.
.
public void setGear(int newValue) {
        gear = newValue;
}
.
.
.
.

We shall start with the most obvious of all , “Public” , which you might have guessed , means free for all. Basically , you can use a public method or a public variable anywhere , within classes or packages. That makes sense isn’t it? When you write an employee class , and your partner is writing a department class , you expect he would use some of your employee class variables in his class. Then why not make public the default? Instead of writing a method to set gear , look above for the code , why don’t we all write like this?

b1.gear = 6;

So what then is the difference between these two lines?

b1.gear = 6;
b1.setGear(6);

As per the code above , there isn’t any. You just assigned a value to the attribute of an instance of a Bicycle class. No big deal. But there is a big deal if you want checks and rules. What if a user assigned the gear as this ,

b1.gear = 1000;

Nothing wrong with it. It is still an integer value assigned to an integer-type variable. But there is something wrong with a bicycle with 1000 gears. From the Yahoo Answers , it seems the most gears possible on a bicycle is 24. So how would you ensure that the value of “gear” is no more than 24? You can’t if the variable is public.

But you could prevent others from accessing the variable directly it , or encapsulate it as OOP textbooks would say , by using “Protect” or “Private” access levels instead of “Public. I have not going through sub-classes so lets just take it that the main difference between “Protect” and “Private” access levels is that “Protect” allows the classes in the same package to access but “Private” variable or method is accessible only in the class in which it is defined.

Reworking Of Our Class

private int gear;
.
.
.
public void setGear(int newValue) {
        gear = newValue;
}
.
.
.
.

Changing Access Levels

Now you could no longer access the gear variable directly from outside as before. The method setGear() must be used in order to change its value. You could now place necessary codes in the function to check if the input value is 24 or less or else reject it. It would look like this.

public int setGear(int newValue) {
       if ( newValue <= 24 ) {
       gear = newValue;
       return 0;
       }
       else {
        return 1;
        }
}

Basically , if the input is less than or equal to 24 , the value would be updated and number 0 would be returned and otherwise , 1 would be returned. Of course there are much better and efficient way of checking but for our example , this would suffice.

Concluding Access Levels

Hope this clear up doubts you may have about the access levels. If you have questions , pls feel free to comment below. Cya!

Beginning OOP Classes | OOP | Class

OOP java Class Example

For the example program on Object-Oriented Programming (OOP) , I will be using Java instead of the usual suspects such as C# or PHP. The syntax of the class will be similar and so are most of the terms I would be using in this post. Here is the code from Oracle website itself , to ensure all the necessary steps are correct.

public class Bicycle {

    // the Bicycle class has three fields or attributes
    public int cadence;
    public int gear;
    public int speed;

    // the Bicycle class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }

    // the Bicycle class has four methods or functions
    public void setCadence(int newValue) {
        cadence = newValue;
    }

    public void setGear(int newValue) {
        gear = newValue;
    }

    public void applyBrake(int decrement) {
        speed -= decrement;
    }

    public void speedUp(int increment) {
        speed += increment;
    }

}

Lets take a look at it before we modify it our own liking. For now , pls ignore the word “public” , which defines the permission for this class , eg.who can access this. We will be going through “public” , “private” , “protected” in future posts. For now just take it that “public” means its open to all , which could be good or bad thing as we shall see.

So we are talking about a type called “Bicycle” , which has 3 attributes or fields to describe it , cadence , gear and speed. Besides that , it can also do a few functions , such as “SpedUp” and so on. I think by now you should be familiar with functions , or at least be able to read it. If not , pls read my previous post one more time here.

OOP Terms : Class vs Instance

Here I would like to pause for a while to take a brief look at the differences between “Class” vs “Instance” of a class in term of OOP. Bicycle , which we have defined above , is a class , so is a man or a woman. But every bicycles are different in their own ways and similarly each man and woman are also different. You and me are both human , to be more precise “Homo Sapien” , but clearly there are differences enough to tell us apart from one another. So how do we create , or instantiate , a new bicycle?

Syntax For Instantiating An OOP Class

ClassName InstanceName = new ConstructorName();

Examples ,

Bicycle b1 = new Bicycle();
Bicycle b2 = new Bicycle();

Constructor is a special type of function that is designed specifically to create an instance. The keyword is “new” which creates a new instance using the constructor given. But if you look above , the constructor has 3 parameters , which means it is not the default constructor rather it has override it. Think of it like saying “She is a lady , but very find one indeed”. So she has gone beyond what is considered a lady , same for the constructor we have here. So do you tell the difference between a constructor and a normal function? A constructor has these attributes ,

  1. It does not return anything , not even void. It is just “public class-name”
  2. The name of the constructor must be same as the name of the class , including the first letter in capital.

To make a new instance of a Bicycle using the constructor given , we would have to change our code ,

Bicycle b1 = new Bicycle(10 , 15 , 6);
Bicycle b2 = new Bicycle(15 , 9 , 2);

We now have 2 new bicycles! They are both bicycles but they are not the same. Whatever you do to one doesn’t affect the other in any way. This is one of the main concepts of OOP so pls besure to understand it.

OOP Class Ends!

That is it for now but I shall be going more in-depth into this example and also on OOP theory. Cya!

Programming Examples

Lets take a good look at actual implementation of the programming languages shall we?

Here is how would you print a string in C.

/* This is a comment. It won't be appearing in the program */
#include  /* This is the header file */

main() /* Beginning of the program , think of it like an index page */
{
    printf ("Hello World!n"); /* prints out "Hello World" and then adds the newline character with n */
}

Here is the same thing in Java.

public class HelloWorld {  // Name of the class and the name of the file must be same 

    public static void main(String[] args) { // this is same as main function above , with more options
        System.out.println("Hello, World"); // Prints out "Hello World" with new line character added with println
    }

}

How about in Ruby?

#!/usr/bin/env ruby //This stype of header file #! is called "She-Bang"

puts "Hello world!" // Simple stuff

What you just seen is how to write a program thats prints out a String called “Hello World” to the console. You might as why not everyone does the same as the last example? Just says put “Hello World” and be done with it? Its not so simple when you are planning an enterprise application.

Its not just a matter of language. Number of people who knows it also matters. One good example is English Language. Its not the best language in the world , it is one of the most difficult languages to learn if you are already an adult. Think of the pronunciation for words such as “hour” , “island” and “potato”. Absolutely inconsistent. Its madness really.

So then why am I typing in it? Well , because it is the number 1 language in the world. Lets not even talk about Chinese Language , number 2 in the world , which writing system has been known to make grown men cry. As you can see , the choice of language for your project must be considered carefully , not only on your expertise of the language but also on how widely it is known.

Just a side not , my favorite language is Sanskrit , a wonderful language . Thanks for reading.