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 is meant by method?
What are the differences between string and stringbuffer?
What is method in research paper?
When a byte datatype is used?
What are the main differences between the java platform and other platforms?
How to read and write image from a file ?
Is nan false?
What is finally block?
What is parsing in java?
If you do not want your class to be inherited by any other class. What would you do?
How many types of methods are there?
What are internal variables?
What is string syntax?
If an object is garbage collected, can it become reachable again?
what are the states associated in the thread? : Java thread