I m doing some problems regarding Return type in java.I m facing some problem . could any help plz.

1. class Plant {
2. String getName() { return "plant"; }
3. Plant getType() { return this; } // what mean 'return this' here
4. }
5. class Flower extends Plant {
6. // insert code here(I have four options A-D. A,C,D are correct here but don't know why? Anyone explain. )
A. Flower getType() { return this; }
B. String getType() { return "this"; }
C. Plant getType() { return this; }
D. Tulip getType() { return new Tulip(); }
7. }
8. class Tulip extends Flower { }

8 Years
Discussion Span
Last Post by Darryl.Burke

"this" refers to the current object.

In your Flower class, this refers to a Flower. That's why method 1 works. 2 works because you're returning a String. 3 works because a Flower is a type of Plant (subclass of Plant), so you are returning a Plant. 4 works because you create a new Tulip object and return it.

Edited by coil: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.