How are this() and super() used with constructors?

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 ?    3 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are different access specifiers in java?

551


Does list allow duplicates in java?

512


Can we declare main () method as non static?

512


Why array is used in java?

505


What does sprintf return?

576






Explain the available thread states in a high-level?

522


Difference between Preemptive scheduling vs. Time slicing?

561


How do you write a conditional statement?

511


What is the abstraction?

577


How to sort double array in java?

579


What is object-oriented programming?

563


What is the use of parse function in java?

503


How do you convert an int to a string in java?

533


State the merge-sort principle and its time complexity.

562


What does escaping a character mean?

528