Classes And Objects

Class Definition

Class is a blueprint in which characteristics (members) and behaviors (functions) are defined.

An example of class definition is:

In the example:

  • class is the keyword for class defining.
  • Person - the name of the class.
  • On lines 3 and 4 class members are declared - the properties that characterize the class.
  • At lines 3 and 4 we define the members as public. public could be replaced with private or protected. The difference between public, private and protected is explained in other tutorials.

Object Creation

Object is an instance created from a class.

Using the defined class we can create objects and set properties.

Output:

Explanation:

  • At lines 2 - 11 a class is defined. It's members are name and age defined at lines 3 and 4.
  • The class also has a function introduceYourself that uses the members via the this keyword.
  • At line 14 an object is created.
  • At lines 17 and 18 values are set to the members.
  • At lines 20 the function introduceYourself is called and a message is printed.