<< Chapter < Page Chapter >> Page >

Objects as parameters

Concept A reference to an object can be an actual parameter whose corresponding formal parameter is declared to be of the same class.As with all parameters, the value of actual parameter is used to initialize the formal parameter, but since it is a reference that ispassed, the method that is called can access fields and methods of the object. This is called reference semantics .

Program: Method07.java

// Learning Object Method07 //    objects as parametersclass Song {     int seconds;      Song(int s) {        seconds = s;     }      double computePrice(double pricePerSecond) {       return seconds * pricePerSecond;     }}  public class Method07 {      static double getPrice(Song s, double ppS) {         return s.computePrice(ppS);    }      public static void main(/*String[] args*/) {        Song song1 = new Song(164);         Song song2 = new Song(103);        double price1 = getPrice(song1, 0.01);         double price2 = getPrice(song2, 0.02);        System.out.println(price1);         System.out.println(price2);    } }

This program computes the cost of a song as the product of its length in seconds and the price per second. A class Song is defined to encapsulate the field seconds and the method computePrice . The method getPrice in the main method receives an object of class Song as a parameter and calls computePrice .

  • Two objects of class Song are instantiated and references to them are assigned to the variables song1 and song2 .
  • The method getPrice is called with two parameters: the first is a reference song1 to an object of class Song , while the second is a value of type double. The actual parameters are used to initialize the formalparameters; check that song1 and s reference the same object.
  • Since the formal parameter s receives a reference to an object of class Song (in this case song1 ), it can be used to call the method computePrice declared in the class.
  • The method returns a value that is assigned to price1 .
  • A second call to the method is executed exactly the same way, except that the actual parameter is the reference contained in song2 .
  • The values of price1 and price2 are printed.

Exercise Modify the program so that discount does not use the explicit parameter s .

Returning objects

Concept A return value can be a reference to an object.

Program: Method08.java

// Learning Object Method08 //    returning objectsclass Song {     int seconds;      Song(int s) {        seconds = s;     }      double computePrice(double pricePerSecond) {       return seconds * pricePerSecond;     }}  public class Method08 {      static Song longer(Song s1, Song s2) {         if (s1.seconds > s2.seconds)             return s1;        else             return s2;    }      public static void main(/*String[] args*/) {        Song song1 = new Song(164);         Song song2 = new Song(103);        Song longerSong  = longer(song1, song2);         double price2 = longerSong.computePrice(0.01);        System.out.println(price2);     }}

This program computes the cost of a song as the product of its length in seconds and the price per second. A class Song is defined to encapsulate the field seconds and the method computePrice . The method longer in the main method receives references to two objects of class Song as parameters and returns a reference to the one with the larger value of the field seconds .

  • Two objects of class Song are instantiated and references to them are assigned to the variables song1 and song2 .
  • The method longer is called with two parameters that are references to objects of class Song . The actual parameters are used to initialize the formalparameters; check that song1 and s1 reference the same object, as do song2 and s2 .
  • Since the formal parameters s1 and s2 receive references to objects of class Song , they can be used to access the fields seconds of each object.
  • The method returns the reference to the object whose field seconds has the larger value. The reference is assigned to the variable longerSong ; check that this reference is to the same object as the reference in song1 .
  • The reference in longerSong is used to call the method computePrice and the value returned is assigned to the variable price2 .
  • The value price2 is printed.

Exercise Modify the program so that discount does not use the explicit parameter s .

Exercise Replace the last declaration and statements of the program by one declaration.

Exercise Write a method to swap two integer values.

Returning locally instantiated objects

Concept When a method terminates, its activation record is deallocated. However, if an object has been instantiated within the method , a reference to the object can be returned to the calling method.

Program: Method09.java

// Learning Object Method09 //    returning locally instantiated objectsclass Song {     int seconds;      Song(int s) {        seconds = s;     }      double computePrice(double pricePerSecond) {       return seconds * pricePerSecond;     }}  public class Method09 {      static Song doubleSong(Song s1) {         Song d = new Song(s1.seconds*2);        return d;     }      public static void main(/*String[] args*/) {         Song song1 = new Song(164);        Song longSong  = doubleSong(song1);     }}

This program computes the cost of a song as the product of its length in seconds and the price per second. A class Song is defined to encapsulate the field seconds and the method computePrice . The method double in the main method receives a reference to an object of class Song as a parameter and returns a reference to an new object of class Song whose field seconds is twice as large.

  • Two objects of class Song are instantiated and references to them are assigned to the variables song1 and song2 .
  • The method doubleSong is called with an actual parameter that is a reference song1 to an object of class Song . The actual parameter is used to initialize the formalparameter; check that song1 and s1 reference the same object.
  • Within the method , the seconds field of the object referenced by s1 is used to instantiate a new object whose reference is assigned to the variable d of class Song .
  • The method returns the reference to the object contained in d ; although d disappears when the activation record is deallocated, the object still exists as does the reference that is returned.
  • The returned reference is assigned to the variable longSong ; check that song1 and longSong reference different objects!

Exercise Replace the last line of the program by: song1 = doubleSong(song1); and explain precisely what happens.

Questions & Answers

Is there any normative that regulates the use of silver nanoparticles?
Damian Reply
what king of growth are you checking .?
Renato
What fields keep nano created devices from performing or assimulating ? Magnetic fields ? Are do they assimilate ?
Stoney Reply
why we need to study biomolecules, molecular biology in nanotechnology?
Adin Reply
?
Kyle
yes I'm doing my masters in nanotechnology, we are being studying all these domains as well..
Adin
why?
Adin
what school?
Kyle
biomolecules are e building blocks of every organics and inorganic materials.
Joe
anyone know any internet site where one can find nanotechnology papers?
Damian Reply
research.net
kanaga
sciencedirect big data base
Ernesto
Introduction about quantum dots in nanotechnology
Praveena Reply
what does nano mean?
Anassong Reply
nano basically means 10^(-9). nanometer is a unit to measure length.
Bharti
do you think it's worthwhile in the long term to study the effects and possibilities of nanotechnology on viral treatment?
Damian Reply
absolutely yes
Daniel
how to know photocatalytic properties of tio2 nanoparticles...what to do now
Akash Reply
it is a goid question and i want to know the answer as well
Maciej
characteristics of micro business
Abigail
for teaching engĺish at school how nano technology help us
Anassong
Do somebody tell me a best nano engineering book for beginners?
s. Reply
there is no specific books for beginners but there is book called principle of nanotechnology
NANO
what is fullerene does it is used to make bukky balls
Devang Reply
are you nano engineer ?
s.
fullerene is a bucky ball aka Carbon 60 molecule. It was name by the architect Fuller. He design the geodesic dome. it resembles a soccer ball.
Tarell
what is the actual application of fullerenes nowadays?
Damian
That is a great question Damian. best way to answer that question is to Google it. there are hundreds of applications for buck minister fullerenes, from medical to aerospace. you can also find plenty of research papers that will give you great detail on the potential applications of fullerenes.
Tarell
what is the Synthesis, properties,and applications of carbon nano chemistry
Abhijith Reply
Mostly, they use nano carbon for electronics and for materials to be strengthened.
Virgil
is Bucky paper clear?
CYNTHIA
carbon nanotubes has various application in fuel cells membrane, current research on cancer drug,and in electronics MEMS and NEMS etc
NANO
so some one know about replacing silicon atom with phosphorous in semiconductors device?
s. Reply
Yeah, it is a pain to say the least. You basically have to heat the substarte up to around 1000 degrees celcius then pass phosphene gas over top of it, which is explosive and toxic by the way, under very low pressure.
Harper
Do you know which machine is used to that process?
s.
how to fabricate graphene ink ?
SUYASH Reply
for screen printed electrodes ?
SUYASH
What is lattice structure?
s. Reply
of graphene you mean?
Ebrahim
or in general
Ebrahim
in general
s.
Graphene has a hexagonal structure
tahir
On having this app for quite a bit time, Haven't realised there's a chat room in it.
Cied
what is biological synthesis of nanoparticles
Sanket Reply
how did you get the value of 2000N.What calculations are needed to arrive at it
Smarajit Reply
Privacy Information Security Software Version 1.1a
Good
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get the best Algebra and trigonometry course in your pocket!





Source:  OpenStax, Learning objects for java (with jeliot). OpenStax CNX. Dec 28, 2009 Download for free at http://cnx.org/content/col10915/1.2
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?

Ask