We will discuss three features of OOP, compare their implementation in Java and JavaScript.

Photo by Christopher Gower on Unsplash

Because the Wiki is already available, I just copied it, do not explain again around:


OOP in Java

As you all know, Java is an object-oriented language, so implementing OOP features is very simple and fast, easy to understand.
Enclosure in Java is demonstrated by giving a way to declare private fields, only accessible internally through get, set functions.

Inheritance and polymorphism are also quite simple, just extend and write the new function override (keep an eye on the access modifier private and protect, I will compare it with JavaScript).

OOP in JavaScript

JavasSript is the opposite, a number of tricks are required to implement these features. In JavaScript, to implement encapsulation, we can create a Constructor Function, which encapsulates all the fields and functions into an object. Usually, you usually declare the following:

With these declarations, closure is not guaranteed. Properties can be accessed and changed from outside. Here, we have to use local variables.

However, this local variable is only accessible in Constructor Function, it is equivalent to private fields in Java. In javascript, there is no way to create protected fields (Only accessible from derived class) like Java and C #. Inheritance is more sida, as I mentioned in the prototype post, in JavaScript there is no extends keyword nor class, we must use the prototype to inherit.


If you are annoyed with JavaScript, you can try learning TypeScript, CoffeeScript or ES6.



Always be nice to anybody who has access to my toothbrush.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store