2

Sorry I'm a beginner just starting out using Java and I've encountered this problem

I have two classes, say they are

class Dog {

}

class Cat {

}

then I created an array that is filled up with either one of those two

Object[][] myAnimal = new Object[4][5];

I want to set a variable equal to a random Object from my array, but I don't know which class it came from. Is there any way to do this?

4
  • 2
    You can check the class of an object at runtime (obj.getClass()), but this doesn't necessarily save you from a poor design. What are you trying to accomplish? Commented Feb 18, 2013 at 2:28
  • if (myAnimalObj instanceof CAT) or if (myAnimalObj instanceof CAT) Commented Feb 18, 2013 at 2:33
  • well I'm trying to simulate a game, where you either have a cat or a dog, and depending on which different things are supposed to happen. I'm looping through my array and trying to set a variable equal to the current cell and then use an if statement to check if its either a dog or cat. Commented Feb 18, 2013 at 2:33
  • jayamohan, how do I set an object equal to a class type i don't know? Thats the problem I'm encountering. Commented Feb 18, 2013 at 2:34

4 Answers 4

3

The ideal solution is to create your own superclass, say Animal which has declares abstract methods. For example, you can do:

abstract class Animal {
    public abstract void speak();
}

Then Cat and Dog each provide their own implementations for the abstract method:

class Cat {
    public void speak() {
        System.out.println("Meow!");
    }
}

class Dog {
    public void speak() {
        System.out.println("Woof!");
    }
}

Now you can simply declare your array as

Animal[][] myAnimal = new Animal[4][5];

Place some animals in the array:

myAnimal[0][0] = new Dog();
myAnimal[0][1] = new Cat();

And then tell the animals to speak:

myAnimal[0][0].speak();
myAnimal[0][1].speak();

I have left out the syntax for main() here, but I hope you can put this together yourself. The concepts used here are called "polymorphism". I strongly suggest you study up on it to help you use this crucial OO concept when designing your code.

Sign up to request clarification or add additional context in comments.

2 Comments

without creating a separate class, can I just call methods like you have listed.Like if (instanceof Dog) { myAnimal[0][0].speak()}
@BillyThompson instanceof is a binary operator. That means it needs two arguments such as if (myAnimal[0][0] instanceof Dog) {myAnimal[0][0].speak();}. And yes, you can do this if Animal has a concrete speak() method. However, it will do the same thing no matter whether the animal is a dog or a cat. The suggestion I give in my answer illustrates the concept of polymorphism. One advantage is that you eliminate the need for if statements such as you suggest. You can also easily add more animals, such as Horse, Cow, Sheep, Duck, etc. with much less code.
1

Well, assuming that your array is filled with instances of one of the two classes, you could do something like:

if(myAnimal[x][x] instanceof Dog) //it is an instance of the Dog class 

You really shouldn't do things like this especially as a beginner though. You said that you're trying to select a random dog or cat? The better way would be to keep two separate arrays, one for dogs and one for cats. Then you can select a random element from the two arrays and you'll know what class you're dealing with.

3 Comments

Ohh ok. well if I do the example you gave, can I set a new object to the current one. Like Dog myDog = myAnimal[x][x] ?
The nice thing about having them in two separate arrays is that you can create an array of class Dog and an array of class Cat. So when you do that, you wouldn't have to create a new object. You could just say, my randomly selected animal is catArray[5]. You can work directory with that element in the array. e.g. catArray[5].someCatFunction()
I should just say that the array solution will work, but what you really might be looking for is to create a class animal like Code-Guru said. That way you could have an array of animals which might be a cat or a dog.
1

Visitor pattern would be really good approach to consider in such situation. Let say, you are making a game that need to react differently for different object (Cat, Dog, Money, etc). So do this:

Make an interface IAnimal that has following definition:

interface IAnimal {
    void visit(IAnimalVisitor visitor, Object param);
}

class Cat implements IAnimal {
    void visit(IAnimalVisitor visitor, Object param) {
        visitor.visit(this, param);
    }
}

class Dog implements  IAnimal {
    void visit(IAnimalVisitor visitor, Object param) {
        visitor.visit(this, param);
    }
}

The IAnimalVisitor will contain one visit() method for each animal type defined. So it will be like:

interface IAnimalVisitor {
    public void visit(Cat c, Object param);
    public void visit(Dog c, Object param);
}

Then you could use put your logic to deal with cat and dog as per you want. For example:

class AnimalFeeder implements IAnimalVisitor {
    public void visit(Cat c, Object param) {
        c.feed(milk);
        c.feed(cat_food);
    }
    public void visit(Dog d, Object param) {
        d.feed(dog_food);
    }
}

Then you can use above food feeding class to feed to you IAnimal array like this:

IAnimal[] animals = new IAnimal[] { new Cat(), new Dog(), 
    new Dog(), new Cat() };

IAnimalVisitor feeder = new AnimalFeeder();
for(IAnimal animal : animals) {
    animal.visit(feeder, null); 
}

You can achieve full freedom to deal with any level of hierarchy within classes. Just put the visit() for each animal class type within IAnimalVisitor.

Comments

0

I think you have to use reflection api, if you want that class instance , its necessary to check any object at runtime ... i think your question is you don't want to put condition static and how to put condition dynamically for different different animal, today its dog,tiger tomrrow its cow or etc... so plz use refelction api

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.