Friday, September 21, 2012

myName My First Object

We discuss enough about Object and Class, now its time to create our own Class and its Object. To create a class all you have to do is,

1. Open the IDE.

2. Create a project. Name it whatever you want.

3. Under solution Right Click on the project => Add => Class.

4. A window will popup. Name the Class Name. Always name the class in Pascal Case. Later I'll post a table on naming conventions. For now Pascal Case in the convention where every First letter of a word is in Upper Case. Like: NameOfMyCompany, MyName etc.

5. Press OK. And you will get a Class named Name;

6. Suppose our client want a application that will accept a firstName, middleName, lastName in three textBox and will return the full name and the reverse of the full name.

7. Finding object field is very important in OOP. You shouldn't have fields that has no values in your program.

8. So in our program we should have three fields which are all string field called firstName,middleName, lastName.


9. Now we write have to write two method that returns the full name and reversed name respectively.

10. So we just blueprinted our problem domain in the Name Class. Why don't we create our UI (User Interface).

11. Design a UI like this:






12. Double click on the button.

13. Now create an object named myName of our Name class. and initialize it. You will have

Name myName = new Name();

14. Now set the value for the class Fields by writing:

myName.firstName = textBox1.Text;

myName.middleName = textBox2.Text;

myName.lastName = textBox3.Text;

textBox4.Text=myName.GetFullName();

textBox5.Text=myName.GetReversedName();

15. In the Name Class write this in the GetFullName method

public string GetFullName()

{

return firstName + " " + middleName + " " + lastName;

}


16. Now write this in the GetReversedName method

public string GetReverseName()

{

string reverseName = "";

string fullName = GetFullName();

for (int index = fullName.Length - 1; index >= 0; index--)

{

reverseName += fullName[index];

}

return reverseName;

}

17. Both methods returns a string. It is the return statement at the bottom of a method.

18. Run the program and give three parts of your name in the textBox and Click show.

19 Tada!!! You will get your full name and reversed name in the bottom text Box's.



Note 1: I suppose you have some basic language knowledge. The code in the GetReversedName is a code block that just takes the last index letter from the fullName string and place it at the starting index of the reverseName string variable. Then it just completes a for loop that traversed reversely and reverse the value of fullname string.

Note 2: Readers if you want some brief description about variable, array, arraylist, list, queue, stack etc. Please comment. I'll provide important word files on them. Otherwise I'll just go ahead assuming you all know these things.

No comments:

Post a Comment