Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public abstract class Item {
- private String name;
- private double weight;
- private double value;
- public String getName() { return name; }
- public double getWeight() { return weight; }
- public double getValue() { return value; }
- public void setName(String name) { this.name = name; }
- public void setWeight(double weight) { this.weight = weight; }
- public void setValue(double value) { this.value = value; }
- }
- public abstract class Container extends Item {
- private Item[] content = new Item[0];
- public Item getItem(int index) { return content[index]; }
- public void addItem(Item item) {
- //Dorzuć nowy przedmiot do tablicy
- int numberOfItems = content.length;
- Item[] tempContent = new Item[numberOfItems+1];
- for (int i = 0; i < numberOfItems; ++i)
- tempContent[i] = content[i];
- tempContent[numberOfItems] = item;
- content = tempContent;
- //Zwiększ wagę kontenera
- double currentWeight = getWeight();
- double newWeight = currentWeight + item.getWeight();
- setWeight(newWeight);
- }
- }
- //Dwie klasy do testowania
- public class Rock extends Item {
- public Rock(double weight, double value) {
- setName("Rock");
- setWeight(weight);
- setValue(value);
- }
- }
- public class Chest extends Container {
- public Chest(double weight, double value) {
- setName("Chest");
- setWeight(weight);
- setValue(value);
- }
- }
- public class Main {
- public static void main(String[] args) {
- Container chest1 = new Chest(10, 20);
- Container chest2 = new Chest(15, 20);
- Item rock1 = new Rock(5, 0);
- Item rock2 = new Rock(5, 0);
- chest1.addItem(rock1);
- chest2.addItem(rock2);
- chest1.addItem(chest2);
- System.out.println("Waga chest1: " + chest1.getWeight());
- }
- }
Add Comment
Please, Sign In to add comment