Navigation menu

16 January 2016

Lesson #02: Implementing classes



A class is a generalized blue-print of an object. It contains properties and behaviors of any object. Let's learn how to create classes. 


Classes are simple to implement. A class has 3 important things:
  1. Name of the class 
  2. Properties of class 
  3. Behaviors of class 


Name: common nouns from our real world. For example: A class of car, fruit, student, animal, etc 

Properties: properties of object of this class. For example: Fruit class may have properties color, size, seeds, taste, minerals, etc 

Behaviors: They are also called procedures or methods. They provide the ability of doing something related to the object of that class. For example: A car class may have a start/stop method. A calculator class may have addition, subtraction and other mathematical operations as behaviors or methods of that class. 


Implementing classes

I'll use Java which is a popular programming language. If we want to make a class of car with properties like bodyColor, speed and fuel with behaviors start(), stop(), accelerate(). We do it like this: 


class Car{

 // Properties

 string bodyColor;

 float speed;

 float fuel;

  // Methods

 void start(){}

 void stop(){}

 void accelerate(){}

}


So this is how you create a class, but still 1 thing is missing. The 'constructor' of the class. What is constructor? Well, a constructor is a special method which initializes your class or creates an object from your class. So lets add the constructor, and it will look like this:


class Car{

 // Properties

 string bodyColor;

 float speed;

 float fuel;

 // Constructor

 public Car(){}

 // Methods

 void start(){}

 void stop(){}

 void accelerate(){}

}

Now your class is ready and it can be used, you can now create an instance of this class which will be our object

No comments:

Post a Comment