popolo - code simple..

Follow

popolo - code simple..

Follow
Object Oriented Programming Basics :: part 1 :: Classes and Objects

Object Oriented Programming Basics :: part 1 :: Classes and Objects

Dimitris Mageiras's photo
Dimitris Mageiras
·May 5, 2022·

1 min read

What is the difference between class and object?

Class is a template, a blueprint, a model from which objects are created. Classes descibe the behavior of objects, classes group similar objects. Objects are instances of classes. Classes are declared once, objects are instantiated during run time.

The class

When we program a class, we describe its properties and methods. Let'see an example:

class Animal {
   color;
}

Animal is a class. It has one property named color. This definition allows the program to instantiate animal objects with different colors (or no color at all). Animal class models animals. But there animals won't have any colors until they are instantiated.

The object

Let's see how we can instantiate a class. We create a new instance with the new keyword.

a = new Animal();

This will create an instance a of the animal. a is the variable name. We can use any valid variable name. an_animal is a valid name:

an_animal = new Animal();

We can give any value to color property.

b = new Animal();
b.color = 'red';

color is a property of the class Animal. We use it a typical variable encapsulated into the Animal model. We can change its value if it's needed.

b.color = 'pink';
 
Share this