Click here to Skip to main content
16,021,041 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
Hi all,

My 11 year old son recently got into Java and Javascript programming, and asks:

"I want to know when and why to use constructors and when to use 'this' and 'super' keywords such as

this.weight = weight;"

Any help would be much appreciated!
Posted

Constructor declaration is same as declaring a method except they use the name of the class and no return type.When you invoked a class constructor it creates a object from the class blueprint.You can have many constructors inside the same class including no argument constructor.Although you didn't create a constructor there is a default constructor associated with that class and you can invoke it to create an object out of it.

about this keyword

Java
private int age;
private String name;

public Student(int Age, int Name) {
    this.age= Age;
    this.name = Name;
}


inside the constructor age is a local copy of the constructor's first argument. To refer to the Point field age, the constructor must use this.age

about super keyword

If your method overrides one of its super class's methods, you can invoke the overridden method through the use of the keyword super.

References :

Providing Constructors for Your Classes
Using the Keyword super
Using the this Keyword
 
Share this answer
 
 
Share this answer
 
It's important that he learns that Java and Javascript are totally different (even though they look very similar). Tell him to stick to one or the other, my advice would be to forget Javascript until he starts creating websites, and stick to Java. A good place for learning all about the language is The Java tutorials[^].
 
Share this answer
 
Richard,

Thanks for the explanation about Java and Javascript. It turns out that my son got started with Javascript but switched to Java shortly afterwards, so looks like he's on the right track!

Thanks again.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900