SHARE
TWEET

Untitled

a guest Jan 28th, 2019 103 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. What is Composition?
  2.  - Composition is the advanced version of Inheritance
  3.  - Instead of extending a class to a subclass, you make the extended
  4.  or parent class into a field and put it in as a parameter of the child
  5.  class constructor
  6.   --> Example:
  7.      public class Parent {
  8.         private String name;
  9.         public Parent(String name) {
  10.             this.name = name;
  11.         }
  12.        
  13.         public void eat() {
  14.             System.out.println("Parent has eaten!");
  15.         }
  16.        
  17.         public void swallow() {
  18.             System.out.println("Parent has swallowed!");
  19.         }
  20.      }
  21.      
  22.      public class Child {
  23.         private Parent parent;
  24.         private String name;
  25.         public Child(Parent parent, Name name) {
  26.             this.parent = parent;
  27.             this.name = name;
  28.         }
  29.        
  30.         public void watchEat() {
  31.             System.out.println("Child watches parent eat!");
  32.             (getParent().)eat();
  33.         }
  34.        
  35.         public Parent getParent() {
  36.             return this.parent;
  37.         }
  38.      }
  39.      
  40.      public class Main {
  41.         Parent daddi = new Parent("Dad");
  42.      
  43.         Child billy = new Child(daddi, "Billy");
  44.         billy.getParent().eat();
  45.             (returns "Parent has eaten!")
  46.         billy.watchEat();
  47.             (returns "Child watches parent eat!"
  48.                 "Parent has eaten!")
  49.      }
  50.  - With this, you can 'extend' from more than one class and use the same
  51.  functions that you would have you actually inherited rather than comp'ed it
  52. - In the example, the main point of composition is in the Main class.
  53. - With the parameter for a class in 'billy', I was able to access the class Parent and its
  54. functions in the child class (billy.getParent().eat();)
  55. - In the class Child, since I set the parameter 'parent' to a field with the value of Parent,
  56. I was able to use that field to also access the functions of the class Parent and program functions
  57. that would internally access the class Parent had the function getParent() been private
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top