Class and Object (Object-Oriented Programming)

  Class and Object

Object-Oriented Programming is easy when you understand the basis on how objects talk to each other to solve a given task.

A class work with an object instance although there are static methods and properties in which we could access inside a class directly without using an instance of the class to access then. Even  the easiest way to distinguish static from instance methods is that they are accessible through the class name that they belong to. If you start typing a class name into Visual Studio, Intellisense will show you what static methods and properties are available to the type itself:

Learn also: What is a List< T >

such as DateTime struct type has DaysInMonth, IsLeepyear , Parse, ParseExact and so on, while String class type has Format , Compare , IsInterned  and more on their list available to that String class without creating an instance and int struct type has Parse, MinValue, MaxValue, Equals and more on their list available to that type.


Examples in code:
namespace StaticAndInstanceMembersOfClass
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DateTime.DaysInMonth(2011, 09);
            String.Format("Hi {0}", "Ayomide");
            int.Parse("4");
        }
    }

}

More about the static accessibility here :
Instance members can only reference the class object why static members are not accessible outside their class code block. 


https://www.maxybyte.com/2017/08/class-and-object-object-oriented.html
Also instance class can reference static fields and methods:

Keys to remember about class

  • You can view a class as a blueprint that has an actual object.
  • A class has members basically they are variable like called properties and it also has methods.
  • An instance of a class is its object referencing the class properties. 
  • The properties that a class contains could be reference outside the class with the class object.
  • Therefore properties in a class are meant to describe attributes common to the object's class.
  • A class could have several objects point to class properties.
  • A class can be created alongside with the default class sharing the same namespace.
  • Class file could also be created separately outside the default class file but  both sharing the same namespace
  • Classes are an important step towards reducing dependency and allowing you to enforce the “separation of concerns”.
  • And from those classes, you can build “instances” that are bound up in a special kind of variable called an object.

 Understanding how a class works with an object


Let's create a Car class under namespace OOPClassObject:

 class Car
        {
            
           public string Make { get; set; } // is just like any variable we have work with thus far; 
           public string Model { get; set; } 
           public int Year { get; set; }
           public string Color { get; set; }
     }


What Car code block does


Class Car is declared just like how any method could be declared and inside its code block we have Class-level Properties such as: Make, Model, Year and Color which we can treat like variables from procedural programming, except it prefix accessibility named "public" and its post-fix get; and set; which means read/write attributes that makes this variable distinct and therefore we refer to them as properties in OOP.
Meanwhile, inside the default class, it is possible to access those properties with the help of the class object instance since the class shares the same namespace with the default class.

namespace OOPClassObject
{
    public partial class Default : System.Web.UI.Page
    {
     
        protected void Page_Load(object sender, EventArgs e)
        {
            Car myNewCar = new Car();    // This is the new instance of the Car
            myNewCar.Make = "oldschool";
            myNewCar.Model = "Mercedez";
            myNewCar.Year = 1986;
            myNewCar.color = "White";
         
        }
    }
}


What  Page_Load method does



  1.  I declared the Car instance and named it MynewCar, its just like how any variable could be declared, in this case it's the actual object from this class.
  2. Each instance now have its own unique values for its properties that I set as I would on any variable. I.e, MyNewCar.Make  = "oldschool" and  the rest in that list.

The Object Instance stores in Memory

Each individual values is stored in sections of memory, and another section of memory hold onto myNewCar as a reference to these memory sections and their values:
https://www.maxybyte.com/2017/08/class-and-object-object-oriented.html
Object Instances stores in memory



















This is exactly how our values are stored in memory and now that we have it in memory we can also retrieve then back from memory whenever we need those values, just like retrieving values from variables.

Now let us modify this class and use its values : Here I will create a very simple application that will select a car from the car lot and displace it, the good thing about it is that if a user spin and get 3 white cars then the user will have access to those 3 cars with just $1000.00  meanwhile each car cost $2000 which should be $6000 in total.
https://www.maxybyte.com/2017/08/class-and-object-object-oriented.html
namespace OOPClassObject
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void displayImage(string[] carColors)
{
Image1.ImageUrl = "/Images/" + carColors[0] + ".jpg";
Image2.ImageUrl = "/Images/" + carColors[1] + ".jpg";
Image3.ImageUrl = "/Images/" + carColors[2] + ".jpg";
}
public void Button1_Click(object sender, EventArgs e)
{
Car MyNewCar = new Car();
MyNewCar.Make = "oldschool";
MyNewCar.Model = "mercedez";
MyNewCar.Year = 1867;
MyNewCar.color = "White";
string[] Cars = new string[] { MyNewCar.carColor(), MyNewCar.carColor(), MyNewCar.carColor() };
displayImage(Cars);
resultLabel.Text = String.Format("The price of this Car is:{0:C},and the colors is:{1}-Make:{2}-Model:{3}-Year:{4}",
evaluateCarPrice(Cars),
typeColor(Cars, MyNewCar), MyNewCar.Make, MyNewCar.Model, MyNewCar.Year);
}
// determine how many white cars
private int determineWhiteCars(string[] Cars)
{
int whiteCount = 0;
if (Cars[0] == "White") whiteCount++;
if (Cars[1] == "White") whiteCount++;
if (Cars[2] == "White") whiteCount++;
return whiteCount;
}
// if there are 3 whites cars in the spin return the price to get the cars with bonus
private int CarsPriceBonus(string[] cars)
{
int whiteCount = determineWhiteCars(cars);
if (whiteCount == 1) return 2000;
if (whiteCount == 2) return 4000;
if (whiteCount == 3) return 1000;
return 0;
}
private int evaluateCarPrice(string[] cars)
{
if (isOtherColors(cars))return 0;
int amount = 0;
if (iswhitecars(cars, out amount)) return amount;
return 0;
}
private bool isOtherColors(string[] cars)
{
if (cars[0] != "White" || cars[1] != "White" || cars[2] != "White") return true;
return false;
}
private bool iswhitecars(string[] cars, out int amount)
{
amount = CarsPriceBonus(cars);
if (amount > 0)
return true;
return false;
}
private string typeColor(string[] cars, Car Mycar)
{
if(cars[0]=="White" && cars[1] == "White" && cars[2] == "White")
return Mycar.color;
return "We are dealing with White Cars";
}
}
class Car
{
Random random = new Random();
public string Make { get; set; } // is just like any variable you have work with thus far;
public string Model { get; set; } //but it is meant to describe the attributes that are common to object's class.
public int Year { get; set; }
public string color { get; set; }
public string carColor()
{
string[] carColor = new string[] {"Green", "Blue", "Yellow", "Gray", "White", "Milk", "Pink"};
return carColor[random.Next(5)];
}
}
}
This will be the result when the user spin and get cars that are not white:
https://www.maxybyte.com/2017/08/class-and-object-object-oriented.html


CONSTRUCTOR

Of course it's a good idea to put a new object into is valid state as soon as possible before you start accessing it normally at the time of instantiation. This would mean that you would want to construct the values for those fields – that represent that state – somewhere on the line of code where the new keyword is used. fortunately, there is a special method for us to do this and this method is called a Constructor.

Learn also: Recursion in C#

Car myNewCar = new Car ("oldschool", "Mercedez" , 1867, "White")
In this case we are populating our Constructor with the values from our Car class-level properties, or simply put this way that we passed in the values that belong to the Car class-level properties as an input parameter at instatiation. 
Obviously Constructor is created whenever we create a new Object , that means we have called on the default , empty constructor by using the empty parentheses: 

protected void Page_Load(object sender, EventArgs e)


  {

            Car myCar = new Car();

            

  }



3 differences between Normal Method and Constructor:

  • It has the same name as the class it belongs to.
  • It has no return value.
  • After the new keyword, It must be called.
To get the code-snippet shortcut for a constructor, type "ctor" and hit the tab key twice.
In this regards, we can take control of what the Constructor does by explicitly writing its implementation details.
Sample Code that will print out our values just like the above code did but this time around we just output our values to examine how to use the constructor within the class level  in a less twisted way: 



namespace Constructor
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Car myCar = new Car("Oldschool", "Mercedez", 1986, "White");
Populated the new object with values through the help of constructor
//Car myCar = new Car();// this still gives undefined values if run
resultLabel.Text = myCar.displayCarDetails();
}
}
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public string Color { get; set; }
public Car(string Make, string Model, int Year, string Color) // Constructor with input parameters
{
this.Make = Make;
this.Model = Model;
this.Year = Year;
this.Color = Color;
}
public Car() Constructor without input parameters
{
this.Make = "undefined";
this.Model = "undefined";
this.Year = 0000;
this.Color = "undefined";
}
public string displayCarDetails()
{
return string.Format("Make:{0}-Model:{1}- Year:{2}- Color:{3}",
this.Make,
this.Model,
this.Year.ToString(),
this.Color);
}
}
}



Save and Run:
https://www.maxybyte.com/2017/08/class-and-object-object-oriented.html




2 comments:

Note: only a member of this blog may post a comment.