Classes
Classes are fundamental to object-oriented programming (OOP). They provide a blueprint for creating objects that encapsulate data and behavior. This guide covers the basics and key aspects of classes in JavaScript, Java, Python, and C++ with practical examples.
What is a Class?β
A class is a template for creating objects (instances) that share common properties and methods. It defines the structure and behavior of the objects. Classes promote code reusability and help in organizing code in a modular way.
Classes in Different Languagesβ
- JavaScript
- Java
- Python
- C++
JavaScript Classes Overviewβ
JavaScript introduced class syntax in ES6. While it is syntactic sugar over JavaScriptβs existing prototype-based inheritance, it provides a clear and readable way to create objects.
Class Declarationβ
// Declaration of a class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Instantiation
const person1 = new Person('Alice', 30);
person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.
Inheritanceβ
class Employee extends Person {
constructor(name, age, jobTitle) {
super(name, age); // Call the parent class constructor
this.jobTitle = jobTitle;
}
describeJob() {
console.log(`I am a ${this.jobTitle}.`);
}
}
const employee1 = new Employee('Bob', 25, 'Software Developer');
employee1.greet(); // Output: Hello, my name is Bob and I am 25 years old.
employee1.describeJob(); // Output: I am a Software Developer.
Java Classes Overviewβ
In Java, classes are the building blocks of OOP. They encapsulate data (fields) and behavior (methods).
Class Declarationβ
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
// Instantiation
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Alice", 30);
person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.
}
}
Inheritanceβ
public class Employee extends Person {
private String jobTitle;
public Employee(String name, int age, String jobTitle) {
super(name, age); // Call the parent class constructor
this.jobTitle = jobTitle;
}
public void describeJob() {
System.out.println("I am a " + jobTitle + ".");
}
}
// Usage
public class Main {
public static void main(String[] args) {
Employee employee1 = new Employee("Bob", 25, "Software Developer");
employee1.greet(); // Output: Hello, my name is Bob and I am 25 years old.
employee1.describeJob(); // Output: I am a Software Developer.
}
}