Advertisement
InCodeWeTrust

Trajdosv2

Jun 10th, 2019
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. public abstract class Item {
  2. private String name;
  3. private double weight;
  4. private double value;
  5.  
  6. public String getName() { return name; }
  7. public double getWeight() { return weight; }
  8. public double getValue() { return value; }
  9.  
  10. public void setName(String name) { this.name = name; }
  11. public void setWeight(double weight) { this.weight = weight; }
  12. public void setValue(double value) { this.value = value; }
  13. }
  14.  
  15. public abstract class Container extends Item {
  16. private Item[] content = new Item[0];
  17.  
  18. public Item getItem(int index) { return content[index]; }
  19. public void addItem(Item item) {
  20. //Dorzuć nowy przedmiot do tablicy
  21. int numberOfItems = content.length;
  22. Item[] tempContent = new Item[numberOfItems+1];
  23. for (int i = 0; i < numberOfItems; ++i)
  24. tempContent[i] = content[i];
  25. tempContent[numberOfItems] = item;
  26. content = tempContent;
  27.  
  28. //Zwiększ wagę kontenera
  29. double currentWeight = getWeight();
  30. double newWeight = currentWeight + item.getWeight();
  31. setWeight(newWeight);
  32. }
  33. }
  34.  
  35. //Dwie klasy do testowania
  36. public class Rock extends Item {
  37. public Rock(double weight, double value) {
  38. setName("Rock");
  39. setWeight(weight);
  40. setValue(value);
  41. }
  42. }
  43. public class Chest extends Container {
  44. public Chest(double weight, double value) {
  45. setName("Chest");
  46. setWeight(weight);
  47. setValue(value);
  48. }
  49. }
  50.  
  51. public class Main {
  52. public static void main(String[] args) {
  53. Container chest1 = new Chest(10, 20);
  54. Container chest2 = new Chest(15, 20);
  55. Item rock1 = new Rock(5, 0);
  56. Item rock2 = new Rock(5, 0);
  57.  
  58. chest1.addItem(rock1);
  59. chest2.addItem(rock2);
  60. chest1.addItem(chest2);
  61.  
  62. System.out.println("Waga chest1: " + chest1.getWeight());
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement