I have a class Supplement for which I've created an array of supplements. Now I want to pass this object into another class Magazine, where one instance of a magazine has many supplements. So I want to be able to pass this array of supplement objects into my Magazine constructor, and write a method in Magazine that I can use to display the Magazine name, Cost, and all the details in the supplement array it has stored. I think I've managed to successfully pass it as a parameter, but how would I be able to write a method that is able to display this array alongside its relevant magazine?
Supplement.java:
package javaapplication1;
import java.util.Arrays;
public class Supplement {
private String supplementname;
private int WeeklySupCost;
private Supplement[] supplements;
public void SetSupplementName(String supplementname){
this.supplementname = supplementname;
};
public void SetWeeklySupCost(int WeeklySupCost){
this.WeeklySupCost = WeeklySupCost;
};
public String GetSupplementName(){
return supplementname;
};
public int GetWeeklyCost(){
return WeeklySupCost;
};
public Supplement(String supplementname, int WeeklySupCost){
this.supplementname = supplementname;
this.WeeklySupCost = WeeklySupCost;
};
public void printSupplements(){
System.out.println("Supplement: " + this.supplementname);
System.out.println("Weekly Cost: " + this.WeeklySupCost);
}
}
Magazine.java:
package javaapplication1;
public class Magazine {
private String magazinename;
private int WeeklyCost;
private Magazine magazineobj;
private Supplement[] supplements;
public void SetMagazineName(String magazinename){
this.magazinename = magazinename;
};
public void SetWeeklyCost(int WeeklyCost){
this.WeeklyCost = WeeklyCost;
};
public String GetMagazineName(){
return magazinename;
};
public int GetWeeklyCost(){
return WeeklyCost;
};
public Magazine(String magazinename, int WeeklyCost, Supplement[] supplements){
this.magazinename = magazinename;
this.WeeklyCost = WeeklyCost;
this.supplements = supplements;
};
public Magazine(){};
public void printMagazine(){
System.out.println("Magazine Name: " + this.magazinename);
System.out.println("Weekly Cost: " + this.WeeklyCost);
System.out.println("Supplements: " + supplements[this.supplements]);
}
}
Main program:
package javaapplication1;
public class JavaApplication1 {
public static void main(String[] args) {
Supplement[] supplements = new Supplement[4];
supplements[0] = new Supplement("Sports Illustrated Special", 4);
supplements[1] = new Supplement("Health and Nutrition", 2);
supplements[2] = new Supplement("Lifestyled", 5);
supplements[3] = new Supplement("Gamer's Update", 3);
Magazine magazineobj = new Magazine("The Wheels Special", 35, supplements);
for(int i = 0; i < 4; i++){
magazineobj.printMagazine();
supplements[i].printSupplements();
}
//System.out.println(magazineobj);
}
}
toString()method for both yourMagazineandSupplementclasses. This method gets called when printing an object to console.