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
What are different access specifiers in java?
Does list allow duplicates in java?
Can we declare main () method as non static?
Why array is used in java?
What does sprintf return?
Explain the available thread states in a high-level?
Difference between Preemptive scheduling vs. Time slicing?
How do you write a conditional statement?
What is the abstraction?
How to sort double array in java?
What is object-oriented programming?
What is the use of parse function in java?
How do you convert an int to a string in java?
State the merge-sort principle and its time complexity.
What does escaping a character mean?