How are this and super used?

Answer Posted / qim2010

this() is used to invoke a constructor of the same class

super() is used to invoke a super class constructor and

Example of using this():
public Pet(int id) {
this.id = id; // “this” means this object
}
public Pet (int id, String type) {
this(id); // calls constructor public Pet(int id)
this.type = type; // ”this” means this object
}

Example of using super():

If a class called “SpecialPet” extends your “Pet” class then
you can
use the keyword “super” to invoke the superclass’s
constructor. E.g.
public SpecialPet(int id) {
super(id); //must be the very first statement in the
constructor.
}

To call a regular method in the super class use:
“super.myMethod( );”. This can be called at any line.

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is primitive array?

522


Does apple use java?

497


Are primitives objects?

566


If I only change the return type, does the method become overloaded?

538


What is Enum in Java?

686






What does += mean in java?

576


What are the ways in which a thread can enter the waiting state?

515


Is string is a keyword in java?

549


Define an applet in java?

632


What is the meaning of immutable regarding string?

524


worst case complexities of Quick sort and Merge sort.

605


Why is java logo a cup of coffee?

625


What is the difference between compile-time polymorphism and runtime polymorphism?

568


What is variable in java?

526


What’s the difference between the methods sleep() and wait()?

543