Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- What is Composition?
- - Composition is the advanced version of Inheritance
- - Instead of extending a class to a subclass, you make the extended
- or parent class into a field and put it in as a parameter of the child
- class constructor
- --> Example:
- public class Parent {
- private String name;
- public Parent(String name) {
- this.name = name;
- }
- public void eat() {
- System.out.println("Parent has eaten!");
- }
- public void swallow() {
- System.out.println("Parent has swallowed!");
- }
- }
- public class Child {
- private Parent parent;
- private String name;
- public Child(Parent parent, Name name) {
- this.parent = parent;
- this.name = name;
- }
- public void watchEat() {
- System.out.println("Child watches parent eat!");
- (getParent().)eat();
- }
- public Parent getParent() {
- return this.parent;
- }
- }
- public class Main {
- Parent daddi = new Parent("Dad");
- Child billy = new Child(daddi, "Billy");
- billy.getParent().eat();
- (returns "Parent has eaten!")
- billy.watchEat();
- (returns "Child watches parent eat!"
- "Parent has eaten!")
- }
- - With this, you can 'extend' from more than one class and use the same
- functions that you would have you actually inherited rather than comp'ed it
- - In the example, the main point of composition is in the Main class.
- - With the parameter for a class in 'billy', I was able to access the class Parent and its
- functions in the child class (billy.getParent().eat();)
- - In the class Child, since I set the parameter 'parent' to a field with the value of Parent,
- I was able to use that field to also access the functions of the class Parent and program functions
- that would internally access the class Parent had the function getParent() been private
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement