Friday 15 February 2013

java - How to wrap different type of object in one single wrapper object -


I have a situation where I have to use the signature of a certain method which can accept different types of objects Could. One solution I think is to use a super class and everyone has to be known as a sub-class though, there is a good elegant design pattern type solution, where we solve it

Once the method gets a certain type of object, then do we know the type of example without checking? Please suggest.

Your question is a little bit, and it can be interpreted in two different ways:

Implement different behavior in one class

Assume that you have two separate classes: Cat and dog . Then you have a class animal and want to do something like this:

  cat cat = new cat (); Dog dog = new dog (); Animal animal = new animal (); Animals.feed (cat); Animals.feed (dog);   

here executes different code based on the type of feed () parameter:

  public class animal {public zero feed (Cat cat) {// ... cat feed} Public Zero Feed (dog dog) {// ... dog feed}}   

It is called.

Applying different behaviors in different classes

On the other hand, you can define an interface pet Provide a method, say field () :

  public interface pet {zero} (); }   

Then to get a different code, cat and dog should apply to pet : Public class cats adhere to the pet {public eats from zero ()} {//}}} public class dog implies pet {public zeroes eat ()} {/ / ...}}

Then your class animal will look like this:

  public class animals {public zero feed ( Pet Pets) {pet.eat (); }}    

No comments:

Post a Comment