-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaggregation.java
82 lines (64 loc) · 1.65 KB
/
aggregation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Java Program to Illustrate Difference between
// Aggregation and Composition
// Importing I/O classes
import java.io.*;
// Class 1
// Engine class which will
// be used by car. so 'Car'
// class will have a field
// of Engine type.
class Engine {
// Method to starting an engine
public void work()
{
// Print statement whenever this method is called
System.out.println(
"Engine of car has been started ");
}
}
// Class 2
// Engine class
final class Car {
// For a car to move,
// it needs to have an engine.
// Composition
private final Engine engine;
// Note: Uncommented part refers to Aggregation
// private Engine engine;
// Constructor of this class
Car(Engine engine)
{
// This keywords refers to same instance
this.engine = engine;
}
// Method
// Car start moving by starting engine
public void move()
{
// if(engine != null)
{
// Calling method for working of engine
engine.work();
// Print statement
System.out.println("Car is moving ");
}
}
}
// Class 3
// Main class
class aggregations {
// Main driver method
public static void main(String[] args)
{
// Making an engine by creating
// an instance of Engine class.
Engine engine = new Engine();
// Making a car with engine so we are
// passing a engine instance as an argument
// while creating instance of Car
Car car = new Car(engine);
// Making car to move by calling
// move() method inside main()
car.move();
}
}