简体   繁体   中英

(JAVA) Initializing object - calling method in one line

public perform Ulti (Location origin, int number) { 

        Map i = new Map(origin, i.getDestination(), number);

} 

The constructor of Map is (Location n, Location m, int k);

My question is, I don't know the destination, but there is a method within Map called getDestination(). I know the origin fed into first parameter , how can I use the method of the newly created object?

note: Map object cannot be null; //so i am unsure of what other placeholder might i use

If you have a variable that holds destination so you have to set it first

for example :

map i = new map(); 
i.setDistination("----");
String distination = i.getDistination();

but in your example you can simply type a destination or get it from other object.

You can do the following thing inside your Map class -

class Map{

   Location origin;
   Location destination;
   int number;

   //create a no argument constructor so that your Map can 
   // be created without any constructor whenever required
   Map(){

   }

   //create a constructor with two argument
   Map(Location origin, int number){
      this.origin = origin;
      this.number = number;
   }  


  //getter and setter methods.

}   

Now you can create Map instance/object like this -

Map i = new Map(origin, number);
Location m = // some code for generating Location as destination
i.setDestination(m);

You can't call and object's method without it being created. And if you could, it wouldn't make sense to pass a value that the object already has per se. What 'is' the destination? If you have other ways to access it just add an empty constructor to Map. Like this

public class Map{
     public Map(){

     }
     //Rest of code
}

And now you can create the object without the destination: Map i = new Map(); and then set the destination once you have it.

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