Object Oriented Programming is completely based on Objects and Classes.
Anything and everthing you see around can be said to be a class. Be it a Car or a Tree or even a Human.
A class can be described as a blueprint which says how an object is going to behave once it is created. And a class has a behaviour and a state.
Sounds Scary?
Let us simplify with the below example :
class Human { string name; string food; string language; public void eat() { System.Console.WriteLine("Eats "+food); } public void speak() { System.Console.WriteLine("Speaks "+language); } }
We have a class named Human. And all of us know humans have a common behavior of speaking and eating. And as said, a class has behaviour and state. We find the two behaviors/methods.
public void eat() { System.Console.WriteLine("Eats "+food); }
public void speak() { System.Console.WriteLine("Speaks "+language); }
But the language and food varies from person to person. Thus we have the states/variables as : food, language and name as it varies from person to person.
string name; string food; string language;
Now, just wait, think for a while. Does the above class Human have any physical existence? I mean Tom, Dick, Harry all are humans and have a physical existance but the above class Human is just a kind of blueprint tellin us how Tom, Dick, Harry is going to behave or react once they are created.
Tom, Dick, Harry are all Objects created from the Human class.
Now, does it ring a bell as in why objects are created from a class? Just imagine God has prepared a Human class stating all the behaviours of Human and thus we are behaving right now.
So, class is just a blueprint stating how an object will behave once it is created.
Below is the way we do in C# :
class Human { string name; string food; string language; public void eat() { System.Console.WriteLine("Eats "+food); } public void speak() { System.Console.WriteLine("Speaks "+language); } } class CreateHuman { public static void Main(string[] args) { Human human = new Human(); } }
We have a class called CreateHuman, inside which we have the main method where objects are created.
class CreateHuman { public static void Main(string[] args) { Human human = new Human(); } }
The first line is :
Human human = new Human();
This is how we create an object. The name of the object is human(off course you can give it any name).
And on the right hand side we have new Human(). Where new keyword means we are going to create a new object.
So, after we create the human object, a block of memory will be allocated to it. And you are all set to insert values to name, food and language.
So, we know the human object has three properties/state i.e. name, food and language. And two behaviors/methods eat() and speak(). But how do we access those?
Behaviors/methods and properties/state of a class can only be accessed using the dot(.) operator of an object.
human.eat();
Where human is the object of Human class. And we have used the dot(.) to access eat().