city.getCityName()
和country.getCountry()
可行。但是如何使用cityname
对象获取country
?像country.getCity().getCityName()
一样?
当country.getCity
被调用时,它将返回null
。
public class Main {
class Country {
private String countryName;
private City city;
public String getCountry(){
return countryName;
}
public void setCountry(String countryName){
this.countryName = countryName;
}
public City getCity(){
return city;
}
public void setCity(City city){
this.city = city;
}
}
class City {
private String cityName;
public String getCityName(){
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
}
public static void main(String[] args) {
City city = new City();
city.setCityName("Chittoor");
Country country = new Country();
country.setCountry("INDIA");
System.out.println("how to get cityName using country object");
}
}
答案 0 :(得分:1)
可能的解决方案可能是这样的:
nums.split(', ')
另一个解决方案是让方法getCity()返回if(mycountry.getCity() != null){
mycountry.getCity().getCityName();
}
。在这种情况下,前面的代码变为:
Optional<City>
您可以找到有关可选here的信息。
答案 1 :(得分:0)
您需要使用setCity方法在国家/地区类别中设置城市对象:
public static void main(String[] args) {
City city = new City();
city.setCityName("Chittoor");
Country country = new Country();
country.setCountry("INDIA");
country.setCity(city);//setting the city
System.out.println("how to get cityName using country object");
System.out.println(country.getCity().getCityName());//printing the city
}
}