<< Chapter < Page Chapter >> Page >

Computation within constructors

Concept Constructors are often used simply for assigning initial values to fields of an object; however, an arbitrary initializing computation can be carried out within the constructor.

Program: Constructor02.java

// Learning Object Constructor02 //    computation within constructorsclass Song {     String name;    int seconds;     double pricePerSecond;    double price;      Song(String n, int s, double p) {         name = n;        seconds = s;         pricePerSecond = p;        price = computePrice();     }      private double computePrice() {        return seconds * pricePerSecond;     }}  public class Constructor02 {     public static void main(/*String[] args*/) {         Song song1 = new Song("Waterloo", 164, 0.01);    } }

The price of a song will not change as long as the fields second and pricePerSecond do not change; to avoid recomputing the price each time it is needed, the class contains a field price whose value is computed within the constructor. The method computePrice is declared to be private because it is needed only by the constructor.

  • The variable song1 is allocated and contains the null value.
  • Memory is allocated for the fields of the object and default values are assigned to the three fields.
  • The constructor is called with three actual parameters; these values are assigned to the formal parameters of the constructor method and the values of the formal parameters are assigned to the three fields.
  • The method computePrice is called; it returns a value which stored in the field price .
  • The constructor returns a reference to the object, which is stored in the variable song1 . The field price can be accessed to obtain the price of a song.

Exercise Modify the class so that no song has a price greater than two currency units.

Overloading constructors

Concept Constructors can be overloaded like other methods. A method is overloaded when there is more than one method with the same name; the parameter signature is used to decide which method to call. For constructors, overloading is usually done when some of the fields of an object can be initialized with default values, although we want to retain the possibility of explicitly supplying all the initial values.

Program: Constructor03.java

// Learning Object Constructor03 //    overloading constructorsclass Song {     String name;    int seconds;     double pricePerSecond;    double price;     final static double DEFAULT_PRICE = 0.005;      Song(String n, int s, double p) {        name = n;         seconds = s;        pricePerSecond = p;         price = computePrice();    }      Song(String n, int s) {         name = n;        seconds = s;         pricePerSecond = DEFAULT_PRICE;        price = computePrice();     }      private double computePrice() {        return seconds * pricePerSecond;     }}  public class Constructor03 {     public static void main(/*String[] args*/) {         Song song1 = new Song("Waterloo", 164, 0.01);        Song song2 = new Song("Fernando", 253);     }}

The website charges a uniform price per second for all songs, except for special offers. We define two constructors, one that specifies a price for special offers and another that uses a default price for ordinary songs.

Questions & Answers

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
yes I'm doing my masters in nanotechnology, we are being studying all these domains as well..
what school?
biomolecules are e building blocks of every organics and inorganic materials.
anyone know any internet site where one can find nanotechnology papers?
Damian Reply
sciencedirect big data base
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.
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
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
characteristics of micro business
for teaching engĺish at school how nano technology help us
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
what is fullerene does it is used to make bukky balls
Devang Reply
are you nano engineer ?
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.
what is the actual application of fullerenes nowadays?
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.
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.
is Bucky paper clear?
carbon nanotubes has various application in fuel cells membrane, current research on cancer drug,and in electronics MEMS and NEMS etc
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.
Do you know which machine is used to that process?
how to fabricate graphene ink ?
for screen printed electrodes ?
What is lattice structure?
s. Reply
of graphene you mean?
or in general
in general
Graphene has a hexagonal structure
On having this app for quite a bit time, Haven't realised there's a chat room in it.
what is biological synthesis of nanoparticles
Sanket Reply
what's the easiest and fastest way to the synthesize AgNP?
Damian 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
Berger describes sociologists as concerned with
Mueller Reply
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?