<< Chapter < Page Chapter >> Page >

Normally in an object-oriented program, all the fields of an object are private and an accessor method like getPrice() is used to access the values of the fields. If this is done, the computation of the price can be placed inthe accessor for the superclass and overridden in accessor for the subclass.

Check this by executing the code and ensuring that the discounted price is computed.

The disadvantage of this solution is that the computation is performed for each access of the field price .

Exercise Develop other solutions for this problem: (a) Call computePrice explicitly after the call to the constructor; (b) Modify getPrice to compute the value of price on the first call and save it for future calls. Summarize the advantages anddisadvantages of all the solutions for this problem.

Constructors with object parameters

Concept An object can contain fields of other user-defined objects, not just of primitive and predefined types. There is nodifference in the constructors, except that references to objects are passed as actual parameters and assigned to fields of the object.

Program: Constructor07.java

// Learning Object Constructor07 //    constructors with object parametersclass Song {     String name;    int seconds;     double pricePerSecond;      Song(String n, int s, double p) {        name = n;         seconds = s;        pricePerSecond = p;     }      public double computePrice() {        return seconds * pricePerSecond;     }}  class SongSet {     public Song track1, track2;      public SongSet(Song t1, Song t2) {        track1 = t1; track2 = t2;     }}  public class Constructor07 {     public static void main(/*String[] args*/) {         Song song1 = new Song("Waterloo", 164, 0.01);        Song song2 = new Song("Fernando", 253, 0.01);         SongSet set = new SongSet(song1, song2);        double price1 = set.track1.computePrice();         double price2 = set.track2.computePrice();    } }

Two objects of type Song are allocated and assigned to fields of another object of type SongSet which has two fields of type Song .

  • Execute the program until the two objects of type Song are allocated and their references assigned to the variables song1 and song2 . (You may want to select Animation / Run Until (ctrl-T) to skip the animation of these declarations.)
  • A variable set is allocated. An object of type SongSet is allocated with default null fields.
  • The constructor for SongSet is called and the references in the two variables song1 and song2 are passed as actual parameters. These references are stored in the two fields track1 and track2 .
  • The reference to the object of class SongSet is returned and stored in set .
  • The prices of the two objects are obtained and stored in the variables price1 and price2 . set is an object of type Songset , while set.track1 is an object of type Song and thus can be used to call the method computePrice .

Exercise Modify the program so that the variables song1 and song2 are not used; instead, the constructors for the songs are embedded within the constructor call for SongSet .

Exercise Modify the program so the constructors for the songs are call within the constructor for SongSet . Under what circumstances would this be done?

Constructors with subclass object parameters

Concept An object of a subclass is also an object of the type of the superclass. Therefore, it can be used when an actual parameter is expected.

Program: Constructor08.java

// Learning Object Constructor08 //    constructors with subclass object parametersclass Song {     String name;    int seconds;     double pricePerSecond;      Song(String n, int s, double p) {        name = n;         seconds = s;        pricePerSecond = p;     }      public double computePrice() {        return seconds * pricePerSecond;     }}  class DiscountSong extends Song {     double discount;      DiscountSong(String n, int s, double p, double d) {        super(n, s, p);         discount = d;    }      public double computePrice() {         return seconds * pricePerSecond * discount;    } }  class SongSet {    public Song track1, track2;      public SongSet(Song t1, Song t2) {         track1 = t1; track2 = t2;    } }  public class Constructor08 {    public static void main(/*String[] args*/) {        Song song1 = new Song("Waterloo", 164, 0.01);         DiscountSong song2 = new DiscountSong("Fernando", 253, 0.01, 0.8);        SongSet set = new SongSet(song1, song2);         double price1 = set.track1.computePrice();        double price2 = set.track2.computePrice();     }}

We allocate two objects, one of type Song and one of type DiscountSong , and use them as actual parameters in the constructor for an object of type SongSet that expects two parameters of type Song .

  • Execute the program until the two objects one of type Song the other of type DiscountSong are allocated and their references assigned to the variables song1 and song2 , respectively.(You may want to select Animation / Run Until (ctrl-T) to skip the animation of these declarations.)
  • The variable set is allocated, and an object of type SongSet is allocated with default null fields.
  • The constructor for SongSet is called and the references in the two variables song1 and song2 are passed as actual parameters. These references are stored in the two fields track1 and track2 .
  • The reference to the object of class SongSet is returned and stored in set .
  • The prices of the two objects are obtained and stored in the variables price1 and price2 . set is an object of type Songset , while set.track1 is an object of type Song and thus can be used to call the method computePrice of that class. Similarly for price2 , except that set.track2 is an object of type DiscountSong ; check that the method computePrice of this class is called.

Exercise Can s2 in the main method be declared to be of type Song ? Explain.

Questions & Answers

what is mutation
Janga Reply
what is a cell
Sifune Reply
how is urine form
Sifune
what is antagonism?
mahase Reply
classification of plants, gymnosperm features.
Linsy Reply
what is the features of gymnosperm
Linsy
how many types of solid did we have
Samuel Reply
what is an ionic bond
Samuel
What is Atoms
Daprince Reply
what is fallopian tube
Merolyn
what is bladder
Merolyn
what's bulbourethral gland
Eduek Reply
urine is formed in the nephron of the renal medulla in the kidney. It starts from filtration, then selective reabsorption and finally secretion
onuoha Reply
State the evolution relation and relevance between endoplasmic reticulum and cytoskeleton as it relates to cell.
Jeremiah
what is heart
Konadu Reply
how is urine formed in human
Konadu
how is urine formed in human
Rahma
what is the diference between a cavity and a canal
Pelagie Reply
what is the causative agent of malaria
Diamond
malaria is caused by an insect called mosquito.
Naomi
Malaria is cause by female anopheles mosquito
Isaac
Malaria is caused by plasmodium Female anopheles mosquitoe is d carrier
Olalekan
a canal is more needed in a root but a cavity is a bad effect
Commander
what are pathogens
Don Reply
In biology, a pathogen (Greek: πάθος pathos "suffering", "passion" and -γενής -genēs "producer of") in the oldest and broadest sense, is anything that can produce disease. A pathogen may also be referred to as an infectious agent, or simply a germ. The term pathogen came into use in the 1880s.[1][2
Zainab
A virus
Commander
Definition of respiration
Muhsin Reply
respiration is the process in which we breath in oxygen and breath out carbon dioxide
Achor
how are lungs work
Commander
where does digestion begins
Achiri Reply
in the mouth
EZEKIEL
what are the functions of follicle stimulating harmones?
Rashima Reply
stimulates the follicle to release the mature ovum into the oviduct
Davonte
what are the functions of Endocrine and pituitary gland
Chinaza
endocrine secrete hormone and regulate body process
Achor
while pituitary gland is an example of endocrine system and it's found in the Brain
Achor
what's biology?
Egbodo Reply
Biology is the study of living organisms, divided into many specialized field that cover their morphology, physiology,anatomy, behaviour,origin and distribution.
Lisah
biology is the study of life.
Alfreda
Biology is the study of how living organisms live and survive in a specific environment
Sifune
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




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