What is a class and an object?
In short
A class is a blueprint that describes a kind of thing, and an object is one real thing made from that blueprint, with its own data.
A class called Dog might say every dog has a name and can bark. Each dog you create from it is an object: one called Rex, another called Bella, each with its own name but sharing the same abilities. The functions that belong to a class are called methods.
Classes help organise bigger programs by keeping data and the code that works on it together. This style is called object-oriented programming, and it's used throughout Python, Java, C#, C++ and JavaScript.
Python
One class, two objects
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return self.name + " says woof"
rex = Dog("Rex")
bella = Dog("Bella")
print(rex.bark())
print(bella.bark())Output
Rex says woof
Bella says woofJavaScript
The same idea in JavaScript
class Dog {
constructor(name) {
this.name = name;
}
bark() {
return `${this.name} says woof`;
}
}
const rex = new Dog("Rex");
const bella = new Dog("Bella");
console.log(rex.bark());
console.log(bella.bark());Output
Rex says woof
Bella says woofLearn it properly
These free lessons teach it step by step, with questions and a program you write yourself.
- Classes and ObjectsLearn Python →
- Methods and AttributesLearn Python →
- Classes and ConstructorsLearn JavaScript →
Try your first lesson free
Codiqo teaches coding in five-minute lessons with real code. Free on the web, iPhone and Android.