Difference of defining properties of an object between js and java


<Below this line, add a link to the EXACT exercise that you are stuck at.>

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>


I just started learning javascript. I learned java before, so I naturally tend to compare these two coding languages.

As for defining properties of an object, in Java you need to define the properties as instance variables explicitly, for example:

public class Student {
           public Student(String name, int id) {
                          studentName = name;
                          studentID = id;
           // some method of the class such as getters and setters....
           /* Private instance variables */

           private String studentName;   /* The student's name           */
           private int studentID;        /* The student's ID number      */
           private double creditsEarned; /* The number of credits earned */
           private boolean paidUp;       /* Whether student is paid up   */


However, in js, when you define an object, you can just write as follows:

function person(firstname,lastname,age,eyecolor) {

in which you do not need to define these properties explicitly.
Do I understand it correctly, or my understanding is not right?

Hey! @citystrawman :slight_smile:
Honestly, that’s an extremely wise idea to compare two languages that often are confused by each other!! Due to similarities in the name and syntax.
But however, in Java, you don’t have to define the properties explicitly either. The reason why you CAN is so that you can access the instance variables later. Refactoring your code here to NOT be instance var-dependent:

public class Student {

           private String name;
           private int id;

           public Student(String name, int id) {
                          this.name = name;
                          this.id = id;

I hope this helps!

I am not quite sure if I understand you: what you mean is that we can use this.name instead of using another word for name (in my example, studentName).

However, what I want to know is why we don’t need to declare

           private String name;
           private int id;

Is that because javascript do not need to declare variables explicitly(like python)?

Yeah it just involves different programming paradigms, but what I was trying to say was that the this.firstname = firstname; -> are instance variables. And it the this keyword is automically creating a variable for you. Just replace this with var:

this.firstname = firstname;
var firstname = firstname;

You’re doing extra work in Java’s “this” keyword refers to the instance and class.
I hope this helps!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.