
Play Store Application link β Java to JavaScript in 13 Steps – App on Google Play
Classes and inheritance are fundamental concepts in object-oriented programming, allowing you to create reusable code and manage complex systems. JavaScript introduced classes in ECMAScript 2015 (ES6), which provide a structured way to define objects with properties and methods.
1. Classes
A class is like a blueprint for creating objects. It defines the properties (data) and methods (functions) that the objects will have.
Example Program:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old`);
}
}
let john = new Person("John", 30);
john.greet(); // Output: "Hello, my name is John and I'm 30 years old"
In this example:
Personis a class with aconstructormethod that initializes thenameandageproperties.- The
greetmethod prints a greeting message. johnis an instance of thePersonclass, created using thenewkeyword, and we call thegreetmethod on it.
Comparison to Java:
In Java, this would be similar to:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void greet() {
System.out.println("Hello, my name is " + name + " and I'm " + age + " years old");
}
}
Person john = new Person("John", 30);
john.greet(); // Output: "Hello, my name is John and I'm 30 years old"
2. Inheritance
Inheritance allows one class (child or subclass) to inherit properties and methods from another class (parent or superclass). This promotes code reuse and establishes a hierarchy.
Example Program:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks`);
}
}
let d = new Dog("Rufus");
d.speak(); // Output: "Rufus barks"
In this example:
Animalis a parent class with aspeakmethod.Dogis a subclass that extendsAnimaland overrides thespeakmethod.dis an instance of theDogclass, and callingspeakshows the overridden behavior.
Comparison to Java:
In Java, this is similar to:
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println(name + " makes a noise");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void speak() {
System.out.println(name + " barks");
}
}
Dog d = new Dog("Rufus");
d.speak(); // Output: "Rufus barks"
Summary
- Classes: Provide a way to define objects with properties and methods. They act as blueprints for creating instances.
- Inheritance: Allows one class to inherit from another, enabling code reuse and creating a hierarchical relationship between classes.
By using classes and inheritance, you can create modular and maintainable code. Classes encapsulate data and behavior, while inheritance helps in extending and reusing code across different parts of your application.
