The title says it all, I got a class in which the variables of the constructor must be private.
public class AdMedia {
private String name;
private int price;
public AdMedia(){}
public AdMedia(String name, int price) {
this.name = name;
this.price = price;
}
that comes with public getter
setter
of the variables of course.
Now the problem comes right after I try to make a child class named Magazine. The class should inherit the name and price but the price is constant for every object initiation. so they won't be on the constructor as the name.
public class Magazine extends AdMedia {
private int area;
private String position;
private String topics;
public Magazine() {}
public Magazine(String name, int size, String position, String topic){
super();
this.size = size;
this.position = position;
this.topic = topic;
}
that also comes with its own getter
setter
too.
I try to put the price inside the constructor but the constructor demand a passed parameter. Using super(name)
also notifies that none of parent constructor have such shape.
This complicates me when I'm trying to get
the name
using parent class method getName()
which might require some downcasting I guess?
I had try to search for the solution but most require me to change the variable's accessibility into protected
. Would there be no other way to do it in private
?
EDIT : I forgot to mention that the result by doing what I wrote above is the unability to access Magazine name, so when I try to downcast-get the name, what returned is a null.
You could write your child constructor either as
public Magazine(String name, int size, String position, String topic){
super();
setName(name);
setPrice(100); // 100 is your constant price
this.size = size;
this.position = position;
this.topic = topic;
}
or as
public Magazine(String name, int size, String position, String topic){
super(name, 100); // 100 is your constant price
this.size = size;
this.position = position;
this.topic = topic;
}
Both ways would however open the possibility to change the price later:
Magazine m = new Magazine("name", 50, "position", "topic");
m.setPrice(10);
If you need to prevent this, you should also override the setPrice()
setter:
public class Magazine extends AdMedia {
...
@Override
public void setPrice(int price) {
// what to do here?
// * you could either silently ignore
// (which might surprise some users expecting to be able to change the price)
// * throw an UnsupportedOperationException
// (which might surprise other users which are not prepared to handle such an exception)
}
}