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
Why object class is super class for every class in java?
Why is the main method declared static?
What is "this" keyword in java? Explain
Explain different ways of creating a thread. Which one would you prefer and why?
Difference between string, stringbuffer and stringbuilder?
What is character in data type?
Is java still relevant?
what is interface in java? Explain
Is string a class in java?
Implementations of set interface?
What is a string token?
what is the difference between thread and runnable types? : Java thread
Can you write a java class that could be used both as an applet as well as an application?
What are the advantages of autoboxing?
How do you start a new line in java?