Classes in Javascript vs Java

Nothing happens outside a class in Java.

To create an object you need a class.

Even to print a simple “Hello World” you need a class.

That is not always the case with Javascript.

You can create objects without using a class.

Everything need not be encapsulated within a class!

There are similarities between the two classes:

Both support inheritance using “extends” keyword

Both have instance fields and methods.

Both support static fields using the “static” keyword and they can be accessed outside the class by using the class name.

But there are more differences between them.

Before looking into the differences let’s see how a sample class looks like in Javascript.

class MyClass {
  // Class properties
  name ; //This is a public property
  static staticProperty = "This is a static property";
  #privateProperty = "This is a private property";
  
  // Constructor
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // Getters and setters
  get age() {
    return this._age;
  }
  set age(value) {
    if (value < 0) {
      throw new Error("Age must be a positive number");
    }
    this._age = value;
  }

  // Prototype methods
  sayHello() {
    console.log(`Hello, my name is ${this.name}.`);
  }

  // Static methods
  static staticMethod() {
    console.log(MyClass.staticProperty);
  }

  // Private methods
  #privateMethod() {
    console.log(this.#privateProperty);
  }
}

//to create objects

const obj = new MyClass("John", 30);
obj.sayHello(); // logs "Hello, my name is John."
MyClass.staticMethod(); // logs "This is a static property"

As you might have noticed there are many differences in the syntax between Java classes and Javascript classes.

Here are the ways in which they differ:

  • The class keyword
  • Instance Fields
  • Access modifiers for instance fields
  • Constructor
  • Getters and Setters
  • Importing a class
  • Class Expressions
  • Creating objects
  • Method overloading
  • Types of classes

Let’s look into them one by one.

The class keyword:

A minor but important difference is the keyword “class”.

It starts with a small case “c” in Javascript whereas in Java it starts with a capital “C” and both are case sensitive.

Instance Fields

Java is a typed language.

So you need to declare the type of an instance field in a class.

But Javascript isn’t.

So you declare an instance field by just including the variable name:

class Person{

name;
age;

}

name and shape are two variables of the class Shape.

There are no access modifiers ! no type declarations!

Looks so empty for a Java developer.

And add on to that you don’t even have to declare them if you are initializing these variables in the constructor.

The following code will work:

class Person{

   constructor(name,age){

             this.name = name;
              this.age = age;
}
}

The variables name and age are automatically declared and assigned the class scope.

Access Modifiers for Instance Fields:

In Java , a variable can have different access modifiers:

  • public – can be accessed outside a class
  • private – can be accessed only inside a class
  • protected – can be accessed in classes within the package and subclasses outside the package.
  • default – can be accessed in classes within the package only.

There are only two access modifiers in Javascript.

And both of them are not enforced using any keyword like ‘public’ or ‘private’.

All the variables you declare inside a class are public by default.

And all the variables you declare by prefixing “#” symbol is private.

For example in the below class:

class Person{
   name;
   #birthdate;

}

name is a public field which can be accessed outside the class.

birthdate is a private field which can only be accessed within the “Person” class.

Constructor:

In Java you create objects with the help of constructors.

Even if you don’t create one Java provides a default one.

In Javascript you use constructors too.

And Javascript provides a default empty constructor too.

But they don’t come with the “Class name” like in Java.

We use , well the very word “constructor” to create a constructor:

class Person{

name;
age;
   constructor(name,age){
      this.name = name;
       this.age = age;
}
}

As you see the constructor is declared using the keyword “constructor’.

Two arguments are passed in the above example .

Again just like in Java , the “this” keyword is used to refer to the current object .

And you can create a new object using “new” keyword just like in Java:

let p = new Person('Vijay',33);

Getters and Setters:

Let’s say you have a private field in a class in Java.

To access that field you create a getter method.

Something like:

Class Person{

   private String name;

   public getName(){

     return name;
  }

}
   

This allows you to have more control over the field access. If you want to enforce any constraints on returning the field you can do it.

And the getter method can follow any valid Java naming convention: getName() , name() , returnName() etc

You can do the same in Javascript on a private variable.

And in addition Javascript gives you two more keywords “get” and “set”

You can use these keywords to define getters and setters in a more elegant and standard way.

class Person {
  name = "Vijay";
  #birthdate = "09 May";

  get birthdate() {
    return this.#birthdate;
  }

  set birthdate(value) {
    this.#birthdate = value;
  }
}

let p = new Person();

console.log(p.birthdate); // Output is 09 May

p.birthdate = "10 March";

console.log(p.birthdate); // Output is 10 March

We have added a getter and setter for the private field “birthdate” in the above class.

And to access it we just need to type p.birthdate , no need to add () at the end of birthdate as we need to do in Java.

Also to set the birthdate we can directly assign it to p.birthdate since we have defined a setter using set keyword .

This is simple , more elegant and provides a standard way of accessing and setting instance fields compared to Java.

Importing a Class:

In Java if you want to access a class you import it using “import statement” in the class you want to access it.

In Javascript also you use import statement .

But there are certain key differences:

  • Exporting the class:

You first need to export the class you want to import. If a class is not exported you cannot access it.

And you expose a class using exports keyword:

export class Person{

}
  • Import using file name

In Java you import a class using its fully qualified name (package followed by class name)

But in Javascript you import using file name:

// Class definition in a file named `my-class.js`
export class MyClass {
  // class implementation
}

// Importing the class in another file
import { MyClass } from './my-class';

const instance = new MyClass();

Also a class name has to match the file name in Java.

But in Javascript they can be different!

Class Expressions:

In JavaScript, you can create a class using a class expression.

A class expression is a way of defining a class that’s created and assigned to a variable, just like any other expression in JavaScript.

There are two types of class expressions: named and unnamed.

Here’s an example of a named class expression:

const MyClass = class MyClass {
  // class implementation
};

const instance = new MyClass();

And here’s an example of an unnamed class expression:

const MyClass = class {
  // class implementation
};

const instance = new MyClass();

There is no such thing as Class Expresssions in Java.

You can’t assign a class to any variable!

Creating Objects:

In Java to create an object you need a class.

You create a class and then create an object for it using “new” operator.

In JavaScript, there are several other ways to create objects:

  1. Object Literals:

The most straightforward way to create an object is using object literals.

An object literal is a comma-separated list of key-value pairs surrounded by curly braces:

const object = { key1: value1, key2: value2, ... };

2. Constructor Function:

Another way to create an object is using a constructor function.

This is not the ‘constructor’ inside a class.

The function acts as a blueprint for creating objects, and the object is created using the new operator:

function Person(param1, param2, ...) {
  this.name= param1;
  this.age= param2;

}

//creating the object
const p = new Person('Vijay', 25);

3. Using Object.create() function:

The Object.create() method creates an object with a specified prototype and properties:

const prototype = {
  method1: function() {...},
  method2: function() {...}
};

const object = Object.create(prototype, {
  property1: {
    value: value1,
    writable: true,
    enumerable: true,
    configurable: true
  },
  property2: {
    value: value2,
    writable: true,
    enumerable: true,
    configurable: true
  }
});

Here method1 and method2 are the two methods in the object

And property1 and property2 are the two properties.

A prototype is first created using the two methods and then the two properties are added while creating the object using Object.create() function.

4. Using prototypes:

function Animal(name, type) {
  this.name = name;
  this.type = type;
}

Animal.prototype.getInfo = function() {
  return `Name: ${this.name}, Type: ${this.type}`;
};

const cat = new Animal("Fluffy", "Cat");
console.log(cat.getInfo());

This is a bit similar to the constructor function way except that you can add new methods using the prototype object.

Method Overloading:

In Java you can have two methods with the same name but different arguments.

This is called method overloading.

Javascript does not support it!

Types of classes:

In Java you have different types of classes:

  • Abstract class
  • Inner class
  • Anonymous class

Javascript has only one type of class.

That’s it!

This post is part of the series :

Java vs Javascript

Here are the other articles:

  1. Say Hello World
  2. Variables

Posted

in

,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading