Object Oriented Programing (OOP) : Creating a Person Class and its Members

By   Tewodros   Date Posted: Oct. 12, 2021  Hits: 1,043   Category:  ASP.NET C#   Total Comment: 0             A+ A-


side

In this OOP exercise we will try to create a person class definition and create properties/Data Fields with Modifier Methods and constructors. 

Class

A class is a representation of real world object like a Person, Vehicle, Student, Employee..

A class is created using the class keyword followed by the name of the class and preceded by the access modifier. Public means this class can used from outside of this class. More on access modifiers in another lesson. 

public class Person  {

 

}

A class has mainly three components

  1. Data Fields
  2. Methods
  3. Constructors

Data Fields 

Stores the state of the attributes of the object that is created when the class is instantiated. 

For example, if the object we want to create is a person, then some of the attributes will be First Name, Last Name, Age, etc. These are what we call the Fields of the class..

public string GivenName ;

Static Fields vs Instance Fields

There are certain type of fields that don't change from object to object no mater how many times we instantiate the object. 

These are constant fields are static by nature and they don't change at all. Const is the keyword we use to create constant fields and they are static by default. 

Example:

private const int VOTE_AGE = 18;    

But instance fields are the regular fields in which their values change from every time we create a new instance of the object.

Example

  public string FamilyName { get; set; }    

Methods

Method on the other hand are used to do some kind of action on the state of the class. In other words they change the state of the class. For Example if a person's name is John, we can change this name to Paul using the methods of the class. 

An accessor method is used to do this. They have direct access to the properties/fields of the class and they are mostly used from outside of the class.

public string GivenName { get; set; }

Other than accessor methods, we can use other types of methods including doing some kind of computation like calculating the age of the person based on property age. 

Constructors

Constructors are used to instantiate the class. They are used to initialize the class with some basic staff. Without constructors we cannot create an object of the class.

Instantiation means creating an instance of the class. We will see how to do this at the end. 

parameterized constructor

We can pass all the parameters that we want to initialize the class with in the constructor when we instantiate the class. 

public Person(string ID)   {

               IDNumber = ID;

           }

If we don't want to initialize the class with default values, we can just use the default constructor as shown below. 

 public Person()

  {          

  }

Let's see everything put together now.

  public class Person     {         

          //PROPERTIES/Data Fields

           public string GivenName { get; set; }       

           public string FamilyName { get; set; }        

           public string IDNumber { get; set; }         

           public int BirthYear { get; set; }    

           private const int VOTE_AGE = 18;     

           private const int SENIOR_AGE = 65;

      

          //Constructors

           public Person()  {          

           }        

           public Person(string ID)   {

               IDNumber = ID;

           }

           public Person(string first, string family, string ID, int birth)     {

               GivenName = first;

               FamilyName = family;

               IDNumber = ID;

               BirthYear = birth;

           }         

 

           //Methods

           public int Age(int year)    {

               return year - BirthYear;

            }         

           public bool CanVote(int year)   {

               int theAge = Age(year);

               return theAge >= VOTE_AGE;

           }

           public bool IsSenior(int year)    {

               return Age(year) >= SENIOR_AGE;

           }          

           public string Tostring()   {

               return "Given name: " + GivenName + "\n"

                   + "Family name: " + FamilyName + "\n"

                   + "ID number: " + IDNumber + "\n"

                   + "Year of birth: " + BirthYear + "\n";

           }          

           public bool Equals(Person per)

           {

               if (per == null)

                   return false;

               else

                   return IDNumber.Equals(per.IDNumber);

           }

       }

 

Now that we have implemented the class definition with all the necessary components of the class, how do we actually use this class. Unless we instantiate it and create objects then it is useless to do all of this.

Class Instantiation

The simples way to create an object of type Person is as follows:

  Person  person  = new Person();

Here person is an object of type Person. 

We used an empty constructor and therefore person has no actual values at this point.

We have two options to initialize an object (or pass values). One using the accessor methods and second one is using the parameterized constructor. 

Using accessor methods

person.GivenName  = “Sam”

person.ID = "1234";

Using parameterized constructor

  Person p2 = new Person("Jane", "Jones", "5678", 1990);

Once we set the values of the person's given name or Id, we can get it back using the same accessor method as follows: 

p1.GivenName

We can also use the calculating methods like Age to get the age of the person. Mind you, we don't store age as a property in the object but we can calculate the age from the birthdate property and return that when asked. 

For example the following code will return the calculated age of a person after calculating the difference of the passed in (current) year value from the birth date. 

 p1.Age(2014)

We can also use another calculating method CanVote() to check if the person can vote (if he/she is above 18 years old)

static void Main(string[] args)     {

           Person p1 = new Person("Sam", "Jones", "1234", 1950);

           Person p2 = new Person("Jane", "Jones", "5678", 2010);

           Console.Write("Age of " + p1.GivenName +   " is " + p1.Age(2014));

           if (p1.IsSenior(2004))

               Console.WriteLine(p1.GivenName +  " can ride the bus for free");

           else

               Console.WriteLine(p1.GivenName +  " must pay to ride the bus");

 

           Console.Write("Age of " + p2.GivenName +  " is " + p2.Age(2004));

           if (p2.CanVote(2004))

               Console.WriteLine(p2.GivenName + " can vote");

           else

               Console.WriteLine(p2.GivenName + " can't vote");   

       }

 

Here is the output we get from the above code. 

Age of Sam is 71. Sam can ride the bus for free

Age of Jane is 11. Jane can't vote

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* wkzpqr

Back to Top