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 the two environment variables that must be set in order to run any java programs?
What are the topics in core java?
What are the different ways of creating thread?
What mechanism does java use for memory management?
What is join () in java?
What are the disadvantages of using inner classes?
Is space a char?
Can we define a package statement after the import statement in java?
What is a programming object?
What is the different between get and post?
How do you input a string in java?
What are strings in physics?
What is composition in java?
How to convert string to char and vice versa?
Can a abstract class be defined without any abstract methods?