How are this and super used?

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 ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is r * in math?

526


how to create multithreaded program? Explain different ways of using thread? When a thread is created and started, what is its initial state? Or extending thread class or implementing runnable interface. Which is better? : Java thread

571


Can a static method be overridden in java?

542


What is dynamic array in java?

498


what is the difference between the methods sleep() and wait()? : Java thread

486






What are structs in java?

537


What is a newline character in java?

535


How do you sort data in java?

495


Is it possible to use string in the switch case?

531


Where is the find and replace?

500


These static constructors are correct ? class A { statc intA() { } static A(int x,int y) { } static A(int x) { } }

579


Does treeset use compareto?

516


Explain working of call by reference function invoking.

568


what are the states associated in the thread? : Java thread

563


What are design patterns and please explain?

549