简体   繁体   中英

Factory, Switch and Random - java

I just started a few weeks ago to learn java. So far I have a problem that I can not get over. I have a mother Class, with 4 extended classes. I have a vector, and want to put in it objects made random using Factory with Switch (I want to use this mode because I do not understand how switch works - I did it with if/else, but not with switch). Can anybody help me? :)

package Tudor;
import java.util.Random;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {
        Random rd = new Random();
        int tipAnimal = rd.nextInt(4);
       Animal list[] = new Animal[5];

        for (int i = 0; i < list.length;; i++) {
            lista[i] = Factory.buildAnimal(tipAnimal);
        }



package Tudor;

public class Animal {
    Object animal;
 public Animal(Object animal) {
        this.animal = animal;
    }


package Tudor;
public class Dog extends Animal {
}

package Tudor;
public class Cat extends Animal {
}

package Tudor;
public class Doberman extends Dog{
}

package Tudor;
public class Shorthair extends Cat{
}

package Tudor;

public class Factory {
    public static Animal buildAnimal ( Object animal) {

        switch (animal) {
}

The thing is that I can not understand how the cases should be in this switch.

Thx. I got it now. I should had used the int insted of Object.

public class Factory {
    public static Animal buildAnimal (int tipAnimal) {  

        switch (tipAnimal) {   
            case 0 :           
                return new Animal();  
            case 1 :
                return  new Dog();
            case 2:
                return new Cat();
            case 3:
                return new Doberman();
            case 4:
                return new Shorthair();
            default: return null;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM