Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Oop

decapling and reusing code

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1 Petros

Petros

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 117 posts

Posted 25 January 2016 - 05:13 PM

Hi guys! Got confused with keeping an object independent from other objects (decapling). However, another feature of oop is inheritance, a feature that allows us to reuse code, so here is where my confusion starts: How can I keep an object independent from others if it has to reuse the code from another object? How do you do this? you send the object from where you need to use a method to the other object or what? for example, suppose I create object2 and object2, needs to use a method from object1, then I make that object2 extend object1. Now I'm able to use the methods in object1! However, wouldn't it be then that object2 depends on object1 to work? Maybe it's a dumb question, but i just came up with that. Thanks for taking the time to give me some clarity on this.


Java Java Doooooo!!!

#2 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts

Posted 26 January 2016 - 01:26 AM

Imagine this being the Object1 class. 

class Object1 {
  public void method1() {
    ...
  }

  public void method2() {
    ...
  }

  public void method3() {
    ...
  }
}

If you desire another class to only use method1, and not be able to use method2 and method3 you could use an interface:

public interface OnlyMethod1 {
  public void method1();
}

And make Object1 use it:

class Object1 implements OnlyMethod1

Now you can create Object1 variables like so:

OnlyMethod1 myObject = Object1();

now, with the 'myobject' variable you can only use method1. You will not be able to use method2 and method3 because you defined the variable as type OnlyMethod1, and OnlyMethod1 doesn't know the methods. Even though behind the scenes 'myObject' is in fact a Object1 instance. (polymorphism iirc)

 

 

Then in Object2 you can't inherit Object1 because, like you said, it will see and be able to use everything from Object1.

Instead, you should pass in a OnlyMethod1 in the constructor and store it in a private variable.

 

 



#3 Petros

Petros

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 117 posts

Posted 31 January 2016 - 06:40 PM

Thanks wim DC, you always come with a good explanation. Sorry I didn't have the time to review your answer until today. But, I write down you'r example and it work just like u say. It helped me a lot. Thanks again.


Java Java Doooooo!!!