Search code examples
javainheritancemethodsextendfriend

Sharing a field method with class


I have a class with objects Now i want to call a function from Box and Toy object from outside of the Container class

class Container
{
   Box box1 = new Box();
   Toy toy1 = new Toy();
   public void open()
   {
      box1.open();
   }
   public void play()
   {
      toy1.play();
   }
}

How can i avoid recreating the methods and just sharing the methods with the Container class. I can not use inheritance because I have 2 or more objects.


Solution

  • You can do it as follows.

    public interface ToyInterface {
        public void play();
    }
    
    public class Toy implements ToyInterface {
        @Override
        public void play() {
            System.out.println("Play toy");
        }
    }
    
    public interface BoxInterface {
        public void open();
    }
    
    public class Box implements BoxInterface {
        @Override
        public void open() {
            System.out.println("open box");
        }
    }
    
    public class Container implements ToyInterface, BoxInterface {
        private BoxInterface box;
        private ToyInterface toy;
    
        public Container() {
            box = new Box();
            toy = new Toy();
        }
    
        public BoxInterface getBox() {
            return box;
        }
    
        public ToyInterface getToy() {
            return toy;
        }
    
        @Override
        public void play() {
            System.out.println("play container");
            this.toy.play();
        }
    
        @Override
        public void open() {
            System.out.println("open container");
            this.box.open();
        }
    }
    

    Then you can access methods of Box and Toy class outside of the Container.

    Container container = new Container();
    container.open();
    container.getBox().open();
    
    container.play();
    container.getToy().play();