Sorry if the title is a little bit confusing! I got this class called Flower that extends a Plant class (for a school assignment) and I have a getType()
method in Plant which just returns this.type
. My issue is that when I run this method on a Flower object, instead of returning the type of Flower, it just returns null
(which is the default return in the Plant class). I was wondering if there is any way to fix this without having to override the method, because that would kind of defeat the whole point of the assignment. The code I have is as below:
Plant Class:
public class Plant {
protected List<String> plot = new ArrayList<>();
private String type;
public Plant() {
//Some stuff here
this.type = null;
}
public String getType() {
return this.type;
}
//More stuff for the class here
Flower Class:
public class Flower extends Plant {
private String type;
private int size;
public Flower(String type) {
this.plot = new ArrayList<>();
this.type = type;
this.size = 0;
//More code not important for the question goes here...
Thank you for your help in advance!
CodePudding user response:
You need to remove the private String type;
from the Flower class.
What is happening is your child class (Flower
) declares a String 'type' and it is hiding the Plant's 'type' field.
Think of it like this - a child can see a parents fields, but a parent can't see a child's fields.
So, when you set type
in Flower
it is not available for Plant
- if you do not declare type
in Flower, when you set it in Flower
it will be visible to Plant
, since that's where it's declared.
CodePudding user response:
The problem you are facing is, that your Plant
class and your Flower
class each have their own type
. And since you don't override the getType()
method in your Flower
class the return value will always be the type
of Plant
which is null
.
You have some options to solve that problem. Either you do the same thing you did with plot
where you make the field protected
and assign it in the constructor of Flower
.
public class Plant {
protected List<String> plot;
protected String type;
public Plant() {
this.plot = new ArrayList<>();
}
public String getType() {
return this.type;
}
}
public class Flower extends Plant {
private int size;
public Flower(String type) {
this.type = type;
this.size = 0;
}
}
Or since every Plant
has a type
you could use the "cleaner" version, where you use super to let Plant
handle the assignment.
public class Plant {
protected String type;
protected List<String> plot;
public Plant(String type) {
this.type = type;
this.plot = new ArrayList<>();
}
public String getType() {
return this.type;
}
}
public class Flower extends Plant {
private int size;
public Flower(String type) {
super(type);
this.size = 0;
}
}