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
How do you find the independent variable?
How to create packages in java?
What are advantages of using Java?s layout managers than windowing systems?
Explain working of call by reference function invoking.
What is hash code collision?
What is difference between hashset and hashmap in java?
how can you catch multiple exceptions in java?
What do you mean by checked exceptions?
Can a class be a super class and a sub-class at the same time? Give example.
What is Session reduplication and how its done?
Is java a pure object oriented language?
What is the importance of main method in Java?
What is the purpose of garbage collection in java? When is it used?
What is type inference in java8?
What are jee technologies?