DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   Java (http://www.daniweb.com/forums/forum9.html)
-   -   Inheritance vs New Method (http://www.daniweb.com/forums/thread84048.html)

no1zson Jul 20th, 2007 12:43 pm
Inheritance vs New Method
 
I want to learn more about how inheritance works, more like I NEED to learn more about it if I am to get any better at this.
In my code I have the value of a cd defined as how many cds are in stock times the price of the cd. I did this in my first class Compactdisk.

Now I have created a sub class that adds a new parameter in to my array, and that all makes sence to me now.

What if I want to alter the output of a method I have already done though? Value for instance. With my new subclass I want to make Value mean (price X stock X restock) where restock is going to be a 5% restocking fee.

I should not have to alter Compactdisk, as CdwArtist is a sub and inherits everything, so I added what you see below to CdwArtist. I think it is right, but how would I then get Inventory to grab this new Value instead of the old Value?
import java.util.*;

public class Inventory
{// begin class Inventory

 public static int maxlength = 0;
  public static CdwArtist[] sort(CdwArtist[] cds)
  {
        Arrays.sort(cds, 0, maxlength);
        return cds;
        }
       
 public static String toString(CdwArtist[] cds)
  {
          String toSend = "\n\n";
       
        for(int i = 0; i < maxlength; i ++)
        toSend = toSend + cds[i].getName() + "\n";
        return toSend;
  }
 
  public static void main(String[] args)
  {//begin method main
 
  // create cd Array
        CdwArtist[] cds = new CdwArtist[100];
       
 
        float totalValue = 0;
       
        Scanner input = new Scanner(System.in); // create scanner
       
        // begin display method
        System.out.print("Enter up to 99 CD Names or STOP to Exit: ");
        String nameInput = input.nextLine(); //read cd name
       
       
        for(int i = 0; i < cds.length && !nameInput.equalsIgnoreCase("STOP"); i++)
        {// begin main While
          cds[i] = new CdwArtist();
          cds[i].setName(nameInput);
         
          System.out.print("Enter CD Artist Name: "); // prompt for artist name
          CdwArtist artist = new CdwArtist(input.nextLine());
                             
          System.out.print("Enter Price of this CD: "); // prompt for price
          cds[i].setPrice(input.nextFloat()); // price input from user.
          while (cds[i].getPrice()<= 0)
                {// begin while
                  System.out.print("Price Must Be Greater Than Zero. Enter Price: ");
                        cds[i].setPrice(input.nextFloat()); // cd price loop from user.
                  } // End while
         
          System.out.print("Enter CD Item Number: "); // prompt for cd item number
          cds[i].setItemno(input.nextInt()); // cds item number input from user
         
          System.out.print("Enter Number of these CDs in Stock: "); // prompt for cd stock
          cds[i].setNstock(input.nextInt()); // cds in stock input from user
         
          System.out.print("\n\nCD "+cds[i].getName()+", Item Number "+cds[i].getItemno()+","); // display name
          System.out.printf(" is worth %c%.2f.",'$', + cds[i].getPrice());//
          System.out.print("\nWe have "+ cds[i].getNstock()+" copies in stock,");
          System.out.printf(" making our inventory for this cd worth %c%.2f.\n", '$', + cds[i].getValue()); //inventory value
       
          if(cds[i].getValue() != -1) totalValue = totalValue + cds[i].getValue();
          System.out.printf("Combined Inventory for all CDs is Worth %c%.2f.\n\n\n", '$', + totalValue);
         
          System.out.print("Enter up to 99 CD Names or STOP to Exit: ");
          input=new Scanner(System.in); // internal loop prompt
          nameInput = input.nextLine(); //name input from user
         
          maxlength ++;
          } // End main While
         
          //System.out.println(toString(cds));
                System.out.println(toString(sort(cds)));
                System.out.print("Ending Program.");

  }// end method main
} // end class Payroll

My first class:
import java.lang.Comparable;

public class Compactdisk implements Comparable
{// begin class

        //InventoryCD class has 5 fields
        private String name; //  Name of cd
        private float price; // price of cd
        private int itemno; // item number of cd
        private int nstock; // how many units in stock       
        private int i; // cd counter for array
        private float value; // value for single cd inventory

       
        //Compact disk class constructor
        public Compactdisk()
       
                // 4 fields need to be set up
                {
                name = "";
                price = 0;
                itemno = 0;
                nstock = 0;
                i = 0;
                value = 0;
                }
               
                // set values
          public void setName(String diskName)
          {
          name = diskName;
          }
                public void setPrice(float cdPrice)
          {
          price = cdPrice;
          }
                public void setItemno(int cdItemno)
          {
          itemno = cdItemno;
          }
                public void setNstock(int cdStock)
          {
          nstock = cdStock;
          }
                public void setValue(float cdValue)
                {
                value = cdValue;
                }
                public void seti(int Count)
                {
                i = Count;
                }
       
               
          // return values
                public String getName()
                {       
                return (name);
                }
                public float getPrice()
                {       
                return (price);
                }
                public int getItemno()
                {       
                return (itemno);
                }
                public int getNstock()
                {       
                return (nstock);
                }
                public int compareTo(Object in)
          {
          return ((Comparable)name.toLowerCase()).compareTo((Comparable)((Compactdisk)in).getName().toLowerCase());
          }
                                       
                // returns indivudual inventory value for a disk
          public float getValue()
          {
          return(price * nstock);
          }
               
                       
         
               
                       
}// end class
and my new sub class, with my added code in bold.
import java.util.*;

public class CdwArtist extends Compactdisk
{
 
 public String artist; // artist performing on cd
 public int restock; // restocking percentage

 
 // Artist constructor
  public CdwArtist()
 {
 artist = "";
 restock = .05
 }
 
 public CdwArtist(String in)
 {
 artist=in;
 }
 
 // get value
 public void setArtist(String in)
 {
 artist=in;
 }
public void setRestock(float cdRestock)
 {
 restock = cdRestock;
 }

 
 // return value
 public String getArtist()
 {
 return (artist);
 }
       
 // returns indivudual inventory value for a disk
          public float getValue()
          {
          return((price * nstock)* restock);
          }
       
       
} //End Class

I was hoping that I could just add a new method with the same name, and since everything is just inherited that my Inventory class would take the last inherited value for Value. It did not work. I still only get the original value that I set up in Compactdisk.
Am I making any sense?

Cerberus Jul 20th, 2007 12:58 pm
Re: Inheritance vs New Method
 
I'll give you a simple example..

Imagine a class:

public class Animal{
  int legs;
  bool tail;
  public Animal(int legs, bool tail){
        this.legs = legs;
        this.tail = tail;
  }
  public void noise(){
      System.out.println("GROWL!");
  }
}

Now we can inherit an 'Animal' and 'override' its noise method.

public class Dog extends Animal{
  public void noise(){
      System.out.println("WOOF"!);
  }
}

Dog inherits all the functionality of Animal and customises the noise method. This is approaching another subject (Polymorphism).

Ezzaral Jul 20th, 2007 1:05 pm
Re: Inheritance vs New Method
 
I do not see any structural problems there. You have overridden the method correctly. There are other issues with the code though and it will not compile as you have it posted. You have defined "restock" as an int, assigned it a double value in the constructor, and also left off the semicolon on the assignment.

You will want to make restock a float or double value for your math to work correctly.

no1zson Jul 20th, 2007 2:20 pm
Re: Inheritance vs New Method
 
I am so stupid. The file I was running was not the file I had compiled. I was coding and compling in one file, running the other and wondering why nothing changed! :o)

Once I did correct that issue it does work, if I take out ".05" and just put in "5" or "05". So my method was right! First time! woo hoo, I am so happy.

Of course I need it to be ".05". When I put the decimal back in it erros and says possible loss of percision, found float, double required. If I change it to doube is says it found double, float required. Here is what it looks like with the syntax corrected.

 public String artist; // artist performing on cd
 public float restock; // restocking percentage

 
 // Artist constructor
  public CdwArtist()
 {
 artist = "";
 restock = .05;
 }
 
 public CdwArtist(String in)
 {
 artist=in;
 }
 
 // get value
 public void setArtist(String in)
 {
 artist=in;
 }
 public void setRestock(float cdRestock)
 {
 restock = cdRestock;
 }
 
 // return value
 public String getArtist()
 {
 return (artist);
 }
       
 // returns indivudual inventory value for a disk
          public float getValue()
          {
          return((price * nstock)* restock);
          }       
       
} //End Class

This is finally fun. I feel like am learning stuff and working through NEW problems for a change!

Ezzaral Jul 20th, 2007 2:30 pm
Re: Inheritance vs New Method
 
The compiler is warning that you are mixing float and double calculations, which affect precision. It you don't want to worry about figuring out how to apply casting in your math expression, just change the type of restock to float and assign it "0.05f". The "f" denotes that it is a float, instead of double which is the default for decimals that you type in as literals.

no1zson Jul 20th, 2007 2:54 pm
Re: Inheritance vs New Method
 
That is a neat trick, thanks for that tip.
Of course it showed me that my math was even more wrong than I though.
I had to change the formula to this:
return(price * nstock)+((price * nstock)* restock);

but with that I am going to say it is close enough, TheGather already pointed out the issue with the counter, so I have nothing more I want to do to this.

I am taking the weekend off to catch up on some reading. I was hoping to start some GUI stuff next week, and that was my whole reason for starting this endeavor. I hope it is as fun as I originally thought it was going to be.

Thanks so much for all your help this week guys. :icon_smile:


All times are GMT -4. The time now is 8:00 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC