Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package oop.has_a;
- import java.util.ArrayList;
- class Motor {
- String type;
- Motor(String s) {
- type = s;
- }
- @Override
- public String toString() {
- return "Motor [type=" + type + "]";
- }
- }
- class Auto {
- Motor motor = null;
- // Kompostion es gibt keine Autos ohne Motor
- Auto(String s) {
- motor = new Motor(s);
- }
- // .. dann wäre aber konsequenterweise auch
- // private Auto() {}
- // angebracht, da man sonst Ferraries auch ohne Motors herstellen könnte.
- // Aggregation es gibt auch Autos ohne Motor
- Auto(Motor motor) {
- this.motor = motor;
- }
- Auto() { motor = null; }
- void builtInMotor(Motor motor)
- {
- this.motor = motor;
- }
- @Override
- public String toString() {
- return "Auto [motor=" + motor + "]";
- }
- }
- class Frabrik {
- public static void main(String[] string) {
- ArrayList<Auto> autos = new ArrayList<>();
- autos.add(new Auto("A"));
- Motor motor = new Motor("B");
- autos.add(new Auto(motor));
- autos.add(new Auto((Motor)null));
- autos.get(2).builtInMotor(new Motor("C"));
- autos.add(new Auto());
- autos.get(3).builtInMotor(new Motor("D"));
- for(Auto auto : autos) {
- System.out.println(auto);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement