A state of object is defined by the difference of properties of an object at different intervals.Lets say, a car is moving, its accelerate property will be true if its not moving it will be false. So these are two states.
class Car{
bool accelerate;
}
Lets have an example of Student class and create some instances so we can understand how instances and classes work and help us.
A super simple student class can have these two properties: name and age.
class Student{
string name;
int age;
public Student(string n, int a){
this.name = n;
this.age = a;
}
}
Notice that we have a customized constructor here. When we initialize class Student, we pass in the parameter the name and age of student to create an object for that particular student.
Now lets create some objects from this class. We will create 2 objects for students Waleed and Shahzad.
Student s1 = new Student("Waleed", 20);
Student s2 = new Student("Shahzad", 17);
Notice the new keyword, this is used to create a new instance of this class. s1 and s2 are completely separate objects. They don't interact in anyway with each other.
Notice the Student class name in the beginning before the variable, which means both s1 and s2 have Student instances, so they both are using the same class to create objects but both instances or objects have different values. s1 has instance for student Waleed and s2 has instance for student Shahzad.
So this is how you create instances or objects of your class.
No comments:
Post a Comment