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 { }

Recommended Answers

All 2 Replies

Member Avatar

"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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.