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)
}
}
Related
My current problem is that I am assigned to created a program that should within the private fields assign tasks[] an array of task. Then within the constructor, that creates the task[] array, giving it the capacity of INITIAL_CAPAITY, and setting numTasks to zero.
I am new and confused on I can tackle this problem
I have tried declaring it within the constructor but there has been no luck.
Task.java
public class Task {
private String name;
private int priority;
private int estMinsToComplete;
public Task(String name, int priority, int estMinsToComplete) {
this.name=name;
this.priority=priority;
this.estMinsToComplete = estMinsToComplete;
}
public String getName() {
return name;
}
public int getPriority() {
return priority;
}
public int getEstMinsToComplete() {
return estMinsToComplete;
}
public void setName(String name) {
this.name = name;
}
public void setEstMinsToComplete(int newestMinsToComplete) {
this.estMinsToComplete = newestMinsToComplete;
}
public String toString() {
return name+","+priority+","+estMinsToComplete;
}
public void increasePriority(int amount) {
if(amount>0) {
this.priority+=amount;
}
}
public void decreasePriority(int amount) {
if (amount>priority) {
this.priority=0;
}
else {
this.priority-=amount;
}
}
}
HoneyDoList.java
public class HoneyDoList extends Task{
private String[] tasks;
//this issue to my knowledge is the line of code above this
private int numTasks;
private int INITIAL_CAPACITY = 5;
public HoneyDoList(String tasks, int numTasks, int INITIAL_CAPACITY,int estMinsToComplete, String name,int priority) {
super(name,priority,estMinsToComplete);
numTasks = 0;
tasks = new String[]{name,priority,estMinsToComplete};
//as well as here^^^^^^^^
}
My expected result is to be able to print out the list through honeydo class. I need to manipulate the code a bit more after adding a few other methods.
Your problem is that your constructor parameter tasks has the same name as that field of your class.
So you assign to the method parameter in your constructor, not to the field. And luckily those two different "tasks" entities have different types, otherwise you would not even notice that something is wrong.
Solution: use
this.tasks = new String...
within the body of the constructor!
And the real answer: you have to pay a lot attention to such subtle details. And by using different names for different things you avoid a whole class of issues!
Also note: it sounds a bit strange that a class named Task contains a list of tasks, which are then strings. The overall design is a bit weird...
Apologies if the question has been asked before, though I did look around and couldn't find an applicable answer to my specific problem. Anyway, I'm trying to model a store that sells desserts which are all derived from a specific Dessert superclass.
When I try to run the program to test my classes, I get an error say "Cookie is not abstract and does not abstract method getPrice() in Dessert public class Cookie extends Dessert. I am getting the same error with another class called Fruit, but it is more or less the exact same as Cookie just with some different member variables and method names.
Here is the Dessert superclass:
public abstract class Dessert {
/** Name of the dessert item. */
protected final String name;
/**
* Constructs a new dessert item.
* #param name Name of the dessert.
*/
public Dessert(String name) {
this.name = name;
}
/**
* Get name of the dessert.
* #return dessert name
*/
public final String getName() {
return name;
}
/**
* Get the price of the dessert.
* #return Dessert price
*/
public abstract double getPrice();
}
And here is the Cookie subclass:
public class Cookie extends Dessert {
private int number;
private double price;
public Cookie (String name, int number, double price) {
super(name);
this.number = number;
this.price = price;
}
public int getItemCount() {
return number;
}
public double getPricePerDozen() {
return (price / 12) * number;
}
}
I can't seem to get the formatting right, but the lines immediately following the colons should be a part of the code block. As well as the curly braces following the block.
Thanks in advance for the help!
Since Cookie.java extends Dessert.java and the latter has an
abstract method getPrice()
Cookie.java must provide a definition for it. (Unless it itself is abstract.
One would do that if we had things such as OatmealCookie
ChocolateChipCookie that would be the definite class.)
I retyped the material quickly due to the problems git markdown and got
these to compile. I assume that the price for Cookie should simply be the
price per dozen and added the appropriate definition to it:
public abstract class Dessert {
protected final String name;
public Dessert (String name) {
this.name = name;
}
public final String getName() {
return name;
}
public abstract double getPrice ();
}
public class Cookie extends Dessert {
private int number;
private double price;
public Cookie (String name, int number, double price) {
super (name);
this.number = number;
this.price = price;
}
public int getItemCount() {
return number;
}
public double getPricePerDozen() {
return (price/12) * number;
}
public double getPrice() {
return getPricePerDozen();
}
}
Your Dessert class has an abstract method double getPrice(), and Cookie extends it, so Cookie needs to implement getPrice() or also be abstract in order to get rid of this error.
The code obviously doesn't compile in its current state, but think of it this way - If we were to instantiate a Cookie, its double getPrice() method is inherited from its super class Dessert, so the method would exist to be called, but it has no implementation in either Cookie or Dessert, so the result of calling it would be unspecified. Java sees this at compilation time, and so prevents you from trying to generate code that is ill-defined.
I have been tasked to declare variables in a constructor but I am not sure how I can go about with this. The request states:
"In the constructor, create the Startrek Asteroids Resort given in the Appendix(see below)"
Lucozade,3,10
Fanta,5,2
Sprite,1,100
Coco,1,1
And here is my constructor:
public Asteroid(String nam, int rat, int cap)
{
name = nam;
rating = rat;
capacity = cap;
}
I had considered creating a text file and creating a method to read the data but I'm not sure if this is what they want.
If you want to save the parameters that are passed in you can just have variables that are declared in your class before hand and save them to these variables.
public class Asteroid {
private String name;
private int rat;
private int cap;
public Asteroid(String name, int rat, int cap) {
this.name = name;
this.rat = rat;
this.cap = cap;
}
}
Well, i was trying to pass arraylist of objects from one activity to another. I have 2 constructors in the class Student.
If, i use, Serializable than the code is like below:
#SuppressWarnings("serial")
public class Student implements Serializable
{
private int studentdID;
private String studentName;
private String studentDept;
public Student(){}
public Student(String name, String dpt)
{ this.studentName = name;
this.studentDept = dpt;}
public Student(int id, String name, String dpt)
{ this.studentdID = id;
this.studentName = name;
this.studentDept = dpt; }
public int getstudentdID() { return studentdID; }
public void setstudentdID(int studentdID) {this.studentdID = studentdID;}
public String getstudentName() { return studentName;}
public void setstudentName(String studentName) {this.studentName = studentName;}
public String getstudentDept() { return studentDept; }
public void setstudentDept(String studentDept) { this.studentDept = studentDept;}
}
But the problem i am facing is that how am i going to do this with parcelable? How am i going to set the values of the variables in class-like i did with Serializable? I mean separately using 2 constructors-one without ID another without the ID?
Did you read how Parcelable works?
You need only one constrcutor for parcelable to read what you pass to it, and Parcelable interface will add a method writeToParcel where you put the data to save.
It's not an automatic process like Serializable, everything is up to you.
The constructor which Parcelable will use will accept only one argument Parcel where you will find some methods like read*(KEY) to read back values.
And in writeToParcel you will write in the Parcel (the argument of the method) the values you want pass to pass with write*(KEY, VALUE).
Parcelable don't care about your constructors or fields.
P.S You will need a CREATOR too. Read some tutorial online to know more about it if you need.
Marco's answer explains why Parcelable doesn't automatically decide what constructor to use - it can't.
However, there is a way around this. Use Parcel.dataAvail(), which
Returns the amount of data remaining to be read from the parcel. That
is, dataSize()-dataPosition().
For example,
public Student(){}
public Student(String name, String dpt)
{
this.studentName = name;
this.studentDept = dpt;}
public Student(int id, String name, String dpt)
{ this.studentdID = id;
this.studentName = name;
this.studentDept = dpt;
}
public Student(Parcel in) {
name = in.readString();
dpt = in.readString();
if(in.dataAvail() > 0) // is there data left to read?
id = in.readInt();
}
^ The above constructor will allow for the necessary variables to be instantiated correctly. Also, you define writeToParcel() something like:
public void writeToParcel(Parcel out) {
out.writeString(name);
out.writeString(dpt);
//0 is the default value of id if you didn't initialize it like
// in the first constructor. If it isn't 0, that means it was initialized.
if(id != 0)
out.writeInt(id);
}
Of course, you'll need to define your CREATOR like so:
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
#u3l solution is not required..how many constructors are there it doesn't matter.
simple it works go as normal implementation.
I mean no special care is required when multiple constructors present in parcelable.
I am working on a homework assignment. I am confused on how it should be done.
The question is:
Create a class called IDCard that contains a person's name, ID number,
and the name of a file containing the person's photogrpah. Write
accessor and mutator methods for each of these fields. Add the
following two overloaded constructors to the class:
public IDCard() public IDCard(String n, int ID, String filename)
Test your program by creating different ojbects using these two
constructors and printing out their values on the console using the
accessor and mutator methods.
I have re-written this so far:
public class IDCard {
String Name, FileName;
int ID;
public static void main(String[] args) {
}
public IDCard()
{
this.Name = getName();
this.FileName = getFileName();
this.ID = getID();
}
public IDCard(String n, int ID, String filename)
{
}
public String getName()
{
return "Jack Smith";
}
public String getFileName()
{
return "Jack.jpg";
}
public int getID()
{
return 555;
}
}
Let's go over the basics:
"Accessor" and "Mutator" are just fancy names fot a getter and a setter.
A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless.
B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.
If you use the static keyword then those variables are common across every instance of IDCard.
A couple of things to bear in mind:
don't add useless comments - they add code clutter and nothing else.
conform to naming conventions, use lower case of variable names - name not Name.