Karn_way
Karn_way

Reputation: 1015

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

i have a condition where i need to use a fixed Method signature which may accept different type of object. one solution i think is to use a super class and let all as a subclasses. however is there any good elegant design pattern kind of solution where we solve this

also once method gets an object of certain type can we know the type of instance without instanceof check ? please suggest.

Upvotes: 1

Views: 2827

Answers (2)

Moritz Petersen
Moritz Petersen

Reputation: 13057

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

Implementing different behavior in one class

Let's assume you have two different classes: Cat and Dog. Then you have a class Animals and want to do something like this:

Cat cat = new Cat();
Dog dog = new Dog();

Animals animals = new Animals();
animals.feed(cat);
animals.feed(dog);

Here feed() executes different code, depending on the parameter type:

public class Animals {
    public void feed(Cat cat) {
        // ... feed the cat
    }

    public void feed(Dog dog) {
        // ... feed the dog
    }
}

This is called method overloading.

Implementing different behavior in different classes

On the other hand, you could define an interface Pet which provides a method, let's say eat():

public interface Pet {
    void eat();
}

Then Cat and Dog should implement Pet to get different behavior:

public class Cat implements Pet {
    public void eat() {
        //...
    }
}

public class Dog implements Pet {
    public void eat() {
        //...
    }
}

Then your class Animals would look like this:

public class Animals {
    public void feed(Pet pet) {
        pet.eat();
    }
}

Upvotes: 1

inquisitive
inquisitive

Reputation: 3639

Implementing an interface is a better pattern than inhering a super class. in that way your classes retain their one-inheritance capacity.

regarding the other question about instanceOf, there is rarely a genuine need to determine the actual class of the object. you can always resort to polymorphism. put all methods that you need to invoke on the object in the interface itself. in that way you will never need to know the actual type.

Upvotes: 1

Related Questions