Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren0
Get all attributes easy way
is it possible to get the values of all attributes of an object without creating a getter method one by one for each attribute? i mean a car object in Vehicle class has name, speed, color, and i would like to get all information at once about this car. Sorry for bad english.
4 Antworten
+ 1
You can create getter for all data of similar type you need and return it in array. Alternatively you can use Object[] array as result of getter and return all data independent of type but it is a bad practice, i do not recommend to code like that.
+ 1
public class Soldier {
String name;
String rank;
Soldier() {
name = "Hartman";
rank = "Gunnery Sergeant";
}
String[] getRankAndName() {
String[] result = new String[2];
result[0] = rank;
result[1] = name;
return result;
}
public static void main(String[] args) {
Soldier s = new Soldier();
String[] text = s.getRankAndName(); //we get name and rank (two attributes) with one method
System.out.println(text[0] + " " + text[1]); //outputs "Gunnery Sergeant Hartman"
}
}
+ 1
i got it, thank you very match!!!!
0
how we get it as sn array? sorry i am new in java.