+ 1

Can we have more than one data type in the same array?

I know arrays are declared like this: datatype[] arrayname=values How can we have different data types? for example: {"dog", 4, "cat", 6 , ... }

16th Sep 2016, 6:21 PM
Daniel de Lizaur
3 Respuestas
+ 3
yes but you have to have an attribute of one class. for example: i have the class Dog in Dog I have the attributes String color, name; int age; double size; then you create the constructor with that attributes. now, in a class Dogs or whatever you want to call it, you have to set an attribute of type Dog for example: private Dog [ ] dogs; (I don't remember very well the sintax :v) an in the constructor of this class you can call the setDogs() method. for example: this is the constructor(){ setDogs(); } private void setDogs(){ here you create an object of class Dog with the array and fill the array. }
16th Sep 2016, 6:33 PM
Felipe Cerquera
Felipe Cerquera - avatar
+ 2
You can make use of polymorphism for that. http://code.sololearn.com/cVZHf80U321P import java.util.List; import java.util.LinkedList; public class Animal { public void eat() { System.out.println("I eat like a generic Animal."); } } class Fish extends Animal { @Override public void eat() { System.out.println("I eat like a fish!"); } } class Goldfish extends Fish { @Override public void eat() { System.out.println("I eat like a goldfish!"); } } class OtherAnimal extends Animal {} public class Program { public static void main(String[] args) { List<Animal> animals = new LinkedList<Animal>(); animals.add(new Animal()); animals.add(new Fish()); animals.add(new Goldfish()); animals.add(new OtherAnimal()); for (Animal currentAnimal : animals) { currentAnimal.eat(); } } }
16th Sep 2016, 8:23 PM
Zen
Zen - avatar
0
ni
17th Sep 2016, 1:40 PM
vivek katta81
vivek katta81 - avatar