Advertisement
Guest User

Untitled

a guest
May 20th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. package oop.has_a;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. class Motor {
  6. String type;
  7.  
  8. Motor(String s) {
  9. type = s;
  10. }
  11.  
  12. @Override
  13. public String toString() {
  14. return "Motor [type=" + type + "]";
  15. }
  16.  
  17. }
  18.  
  19. class Auto {
  20. Motor motor = null;
  21.  
  22. // Kompostion es gibt keine Autos ohne Motor
  23. Auto(String s) {
  24. motor = new Motor(s);
  25. }
  26. // .. dann wäre aber konsequenterweise auch
  27. // private Auto() {}
  28. // angebracht, da man sonst Ferraries auch ohne Motors herstellen könnte.
  29.  
  30.  
  31. // Aggregation es gibt auch Autos ohne Motor
  32. Auto(Motor motor) {
  33. this.motor = motor;
  34. }
  35. Auto() { motor = null; }
  36.  
  37. void builtInMotor(Motor motor)
  38. {
  39. this.motor = motor;
  40. }
  41.  
  42. @Override
  43. public String toString() {
  44. return "Auto [motor=" + motor + "]";
  45. }
  46. }
  47.  
  48.  
  49. class Frabrik {
  50. public static void main(String[] string) {
  51.  
  52. ArrayList<Auto> autos = new ArrayList<>();
  53.  
  54. autos.add(new Auto("A"));
  55. Motor motor = new Motor("B");
  56. autos.add(new Auto(motor));
  57. autos.add(new Auto((Motor)null));
  58. autos.get(2).builtInMotor(new Motor("C"));
  59. autos.add(new Auto());
  60. autos.get(3).builtInMotor(new Motor("D"));
  61.  
  62.  
  63. for(Auto auto : autos) {
  64. System.out.println(auto);
  65. }
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement