Results 1 to 13 of 13
  1. #1
    xf021209 is offline Member
    Join Date
    Mar 2009
    Posts
    12
    Rep Power
    0

    Default subclass troubles

    I like many am taking a Java course and like a lot, I'm just not understanding it. My assignment due today does not work. The assignment users a subclass that is returning null instead of the value I need from the superclass. I can't figure out what's wrong and why I'm getting a null return. Any help would be greatly appreceated. Thanks for any help provided.

    Java Code:
    /*
     * Program Class Name: InventoryProgram
     * InventoryProgram.java
     * InventoryProgram.class
     *
     * This is the main class that is part of a non-GUI based Java application.
     * This class calls the Products class to compute the inventory.
     * This class then displays the inventory information and results of
     * the computations.
     *
     * Author: Todd C.
     * Date: April 18th, 2009
     */
    import java.util.Arrays; // allows manipulation of arrays
    public class InventoryProgram // main class
    {
        public static void main(String[] args) // start execution
        {
            // put the values into variable arrays
            String InvTitle[] = {"Beginning Programming with Java for DUMMIES", "The Zoo", "Ace of Spades","The Clock Tower", "Java How To Program", "Java All In One Desk Reference For DUMMIES", "The Mad Scientists Club"}; // Book Titles
            String InvPub[] = {"Willy Publishing Inc.", "Ivory Publishing Co.", "Postal Publishing Inc.","Dugan Books","Willy Publishing Inc.", "Willy Publishing Inc.", "Quicknight Publishers"};// publishers
            int InvNum[] = {52499, 33847, 99930, 11223, 39282, 98372, 10293};  // InvNum is the item number
            int InvQty[] = {23, 9, 39, 21, 13, 8, 12}; // InvQty is the inventory quantity for this item
            double InvPrice[] = {24.99, 28.55, 39.95, 13.85, 29.95, 17.97, 14.28}; // Self explanitory
    
            String allProdInfo[]; // Product array
            allProdInfo = new String[InvNum.length]; // set allProdInfo dimension
    
    
            // Print the title early so it doesn't duplicate
            System.out.printf("\nInventory Program for Books-R-Us\n--------------------------------\n");
    
    
            // Go calc the information and shove it into allProdInfo[] so you can sort it out right.
       for ( int Inven = 0; Inven < InvNum.length; Inven++) // Use a 'for' loop and array.length
       {
            // pass the data to the constructor in the Products class
            Products book = new Products(InvNum[Inven],InvTitle[Inven], InvPub[Inven],InvQty[Inven],InvPrice[Inven]);
    
            // Since convering the numerics to string values the printf %2.f won't work here
            double tmpValue = InvQty[Inven] * InvPrice[Inven]; // use a simple multiply and devide to set to two d. places
            double QtXPrice = Math.rint(tmpValue * 100) / 100; // simple two line rounding works great with Math class
    
            // Put all the data into an a product array for sorting
            allProdInfo[Inven] = book.getBookTitle() + "\n   SKU# " + book.getBookItem() + "\n   QTY: " + (int)book.getBookStock() + "\n   PRICE: $" + book.getBookPrice() + "\n   INVETORY VALUE: $" + QtXPrice;
       } // end for loop
    
    
           // You have the data, combined. Now go sort it in proper order at method modifyArray
           modifyArray( allProdInfo ); // calls the method below to modify into alphabetical order
    
    
           // Display the results
      for ( int Inven = 0; Inven < InvNum.length; Inven++) // Use a 'for' loop and array.length
      {
           System.out.printf(Inven + 1 + ". " + allProdInfo[Inven] + "\n"); // Show what the inventory is
           
           InheritProducts inheritProducts = new InheritProducts(); // instantiate the object
           inheritProducts.PrintPublisher(); // call the method of the object
      }    // end for loop
    
    
           // go calculate the total of the inventory
           double calcTotal = 0; // initialize the variable to hold the total of inventory
      for ( int Inven = 0; Inven < InvNum.length; Inven++)  // Use a 'for' loop and array.length
     {
           Products SumTotal = new Products(InvQty[Inven],InvPrice[Inven]); // only need Inven and Price for constructor
           calcTotal = calcTotal + SumTotal.returnSumTotalValue(); // as the values are returned from the method, total them into calcTotal
     } // end for loop
    
           // Display the total value of the inventory
           System.out.printf("TOTAL CURRENT INVENTORY VALUE: $%.2f\n\n", calcTotal);
     } // end method main
    
    
        // Method to sort the allProdInfo array
        public static void modifyArray(String[] allProdInfo) // method modifyArray
        {
            Arrays.sort(allProdInfo); // sort the aalProdInfo array
        }  // end method modifyArray
    
    }  // end InventoryProgram class
    
    
    
    
    /*
     * Program Class Name: Products
     * Products.java
     * Products.class
     *
     * This is a class that is part of a non-GUI based Java application.
     * This class stores and computes an inventory of items in an array.
     *
     * Author: Todd C.
     * Date: April 18th, 2009
     */
    public class Products // class Products
    {
        private String bookTitle;  // declare instance variables
        private String bookPub;
        private int bookStock;
        private double bookPrice;
        private int bookItem;
        private double InvQty;
        private double sumInvTotal; // these variables are for the total value of the inventory
        private int sumInvStock;
        private double sumInvPrice;
        private double price;
    
    
       // declare emtpy consturctor for the Publisher class
        public Products(){}
    
    
        // declare constructor
        public Products (int item, String title, String pub, int stock, double price)
        {
            bookTitle = title; // pass the data from the main class to the variables
            bookPub = pub;
            bookStock = stock;
            bookPrice = price;
            bookItem  = item;
        }
    
    
    
         // delcare another constructor. This one is for the total inventory value so it only needs # in stock and price
        public Products(int nStock, double nPrice) // declare another constructor with different items
        {
            sumInvTotal = 0;
            sumInvStock = nStock;
            sumInvPrice = nPrice;
        }
    
    
        
        // set book Title method
        public void setBookTitle(String title)
        {
            bookTitle = title;
        } //end method  setBookTitle
    
        //return book Title method
        public String getBookTitle()
        {
            return bookTitle;
        } //end method getBookTitle
    
    
    
    // set book publisher method
        public void setBookPub(String pub)
        {
            bookPub = pub;
        } //end method  setBookPub
    
        //return book pub method
        public String getBookPub()
        {
            return bookPub;
        } //end method getBookPub
    
    
    
        //set book Stock method
        public void setBookStock(int stock)
        {
            bookStock = stock;
        } //end method setBookStock
    
        //return BookStock method
        public double getBookStock()
        {
            return bookStock;
        } //end method get Bookstock
    
    
    
        public void setBookPrice(double price)
        {
            bookPrice = price;
        } //end method setBookPrice
    
        //return bookPrice method
        public double getBookPrice()
        {
            return bookPrice;
        } //end method get Book Price
    
    
    
        public void setBookItem(int item)
        {
            bookItem = item;
        } //end method setbookItem
    
        //return book item method
        public int getBookItem()
        {
            return bookItem;
        } //end  method getBookItem
    
    
    
        //calculate inventory value method
        public double value()
        {
            return bookPrice * bookStock;
        } //end method value
    
    
    
        // calculate the entire inventory value and return the results
        public double returnSumTotalValue()
        {
            sumInvTotal = (sumInvStock * sumInvPrice);
            return sumInvTotal;
        } // end method returnSumTotalValue
    
    
    } // end Products class
    
    
    
    
    /*
     * Program Class Name: InheritProducts
     * InheritProducts.java
     * InheritProducts.class
     *
     * This is the subclass that is part of a non-GUI based Java application.
     * This class calls the Products class.
     * This class then returns the results of
     * for the publisher.
     *
     * Author: Todd C.
     * Date: April 18th, 2009
     */
    //public class Publisher {
    
    public class InheritProducts extends Products // whatever
    {
       public void PrintPublisher()
        {
           System.out.println("   PUBLISHER OF " + super.getBookPub() + "\n");
        } // end PrintPublisher which doesn't work
    
    } // end class

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You need to create a subclass that can take the place of the Products object that your InventoryProgram is currently using. Thus this new class that inherits from Products needs to have a constructor with a similar signature as the one used for Products, and the first line of this constructor should be a call to the equivalent Products constructor via a call to super(...) constructor:
    Java Code:
      public InheritProducts(int item, String title, String pub, int stock,
          double price)
      {
        super(item, title, pub, stock, price);
      }
      //... etc
    Then the inherited class can use all of the methods from the super class and will hold all the data that you currently have in your Products object.

    In other words, your book object should be an InheritedProducts object, and there should be no inheritedProducts object as books will do it all.

  3. #3
    xf021209 is offline Member
    Join Date
    Mar 2009
    Posts
    12
    Rep Power
    0

    Default

    Thank you for responding but I'm not understanding. You say I need to create a subclass. That's what the InheritProducts class is supposed to be, my subclass.


    Quote Originally Posted by Fubarable View Post
    You need to create a subclass that can take the place of the Products object that your InventoryProgram is currently using. Thus this new class that inherits from Products needs to have a constructor with a similar signature as the one used for Products, and the first line of this constructor should be a call to the equivalent Products constructor via a call to super(...) constructor:
    Java Code:
      public InheritProducts(int item, String title, String pub, int stock,
          double price)
      {
        super(item, title, pub, stock, price);
      }
      //... etc
    Then the inherited class can use all of the methods from the super class and will hold all the data that you currently have in your Products object.

    In other words, your book object should be an InheritedProducts object, and there should be no inheritedProducts object as books will do it all.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Right, you've got a start, but it's not enough. Your subclass needs to be able to take the place of the Products class so that your main application has no Products objects but instead has only an object of the InheritedProducts type. Thus you need to give your current subclass at the very least the constructor that I've posted.

    Currently you have two objects doing what one is supposed to be doing. Your InheritedProducts object, inheritedProducts, has absolutely no knowledge of the state of your Products object, book, and that make sense since they are two completely different objects. So of course you'll see a null when you call super.getBookPub in the inherited object.

    If you make your InheritedProduct class more robust it will be able to do its work and Product's work and the main class, InventoryProgram, will only need one object, book, that is an InheritedProduct object to do all of its work.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Another problem I see is that in your InventoryProgram class your comment states that allProdInfo is a Product array, but you have declared it as a String array. Are you sure that this is correct?
    Java Code:
    String allProdInfo[]; // Product array 
                          //  -- !! this is not a Product array

  6. #6
    xf021209 is offline Member
    Join Date
    Mar 2009
    Posts
    12
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Another problem I see is that in your InventoryProgram class your comment states that allProdInfo is a Product array, but you have declared it as a String array. Are you sure that this is correct?
    Java Code:
    String allProdInfo[]; // Product array 
                          //  -- !! this is not a Product array
    I did that so I could use my sort routine to put the products in alphabetical order. I wasn't too concerned about that since that is done after all the calculations are complete. Would that be correct? I'm pretty frustrated with the entire thing at this point. Sorry, just been working on this for four days and it's driving me a little crazy. I appreceate your help.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    I believe that since you have an array of String, you lose all of the Product functionality that you otherwise would have had. I think that you're much better off using an array of Product, or even better an array of InheritedProduct.

  8. #8
    xf021209 is offline Member
    Join Date
    Mar 2009
    Posts
    12
    Rep Power
    0

    Default

    So I've added the following to my subclass InheritProducts

    public InheritProducts(String pub, double price)
    {

    }

    nothing more at this point. NetBeans complains about a problem with InventoryProgram the main class.

    InheritProducts inheritProducts = new InheritProducts(); // instantiate the object
    inheritProducts.PrintPublisher(); // call the method of the object

    NetBeans complains - cannot find symbol. symbol: constructor InheritProducts() location: class InheritProducts

    I tried entering in the super(pub,price);

    and the original error in main remains but I also get - cannot find symbol symbol: constructor Products(java.lang.String,double) location: class Products.

    I'm not sure what to do about the first error. The second sounds like I need a constructor with pub,price in it in the Products class. When I add in the consturctor into the Products class with (String pub, double price) all the errors go away except the first one in the InventoryProgram main class. That one remains, and the program won't run - returning with:

    run:

    Inventory Program for Books-R-Us
    --------------------------------
    1. Ace of Spades
    SKU# 99930
    QTY: 39
    PRICE: $39.95
    INVETORY VALUE: $1558.05
    Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
    symbol : constructor InheritProducts()
    location: class InheritProducts
    at InventoryProgram.main(InventoryProgram.java:58)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 1 second)






    Quote Originally Posted by Fubarable View Post
    Right, you've got a start, but it's not enough. Your subclass needs to be able to take the place of the Products class so that your main application has no Products objects but instead has only an object of the InheritedProducts type. Thus you need to give your current subclass at the very least the constructor that I've posted.

    Currently you have two objects doing what one is supposed to be doing. Your InheritedProducts object, inheritedProducts, has absolutely no knowledge of the state of your Products object, book, and that make sense since they are two completely different objects. So of course you'll see a null when you call super.getBookPub in the inherited object.

    If you make your InheritedProduct class more robust it will be able to do its work and Product's work and the main class, InventoryProgram, will only need one object, book, that is an InheritedProduct object to do all of its work.

  9. #9
    xf021209 is offline Member
    Join Date
    Mar 2009
    Posts
    12
    Rep Power
    0

    Default

    I don't know what those are. Can you give me an example?

    Thanks,

    Todd


    Quote Originally Posted by Fubarable View Post
    I believe that since you have an array of String, you lose all of the Product functionality that you otherwise would have had. I think that you're much better off using an array of Product, or even better an array of InheritedProduct.

  10. #10
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    Java Code:
    Product allProdInfo[];
    If you want to make the array sortable then make Product implement the Comparable<Product> interface.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Here's an example that's similar to yours, but not the same. The idea is to give you an example for you to study, but not to give you the exact solution for your homework so you can apply what you learn to your own work.

    Here I have a class called MyClass that holds three bits of information, an int called foo, a String called bar and another String called baz. It has a showData() method that returns a String that displays the foo number and the bar String but doesn't show the baz String. Finally, it has a constructor that takes three parameters, an int, String, and String, and with these initializes the variables in the object.

    Now I'll subclass this class and call it MyChildClass. This class has an updated showData() method that returns everything from its parent class (via a call to super.showData()) as well as showing the baz String. I'll also need to give it a constructor with the same signature as its parent constructor and use the parameters passed to call the super constructor.

    Now I'll create a MainClass that holds an array of MyClass objects but will fill it with MyChildClass objects. For eg.,

    MyClass.java
    Java Code:
    public class MyClass
    {
      private int foo;
      private String bar;
      private String baz;
      
      public MyClass(int foo, String bar, String baz)
      {
        super();
        this.foo = foo;
        this.bar = bar;
        this.baz = baz;
      }
    
      public int getFoo()
      {
        return foo;
      }
    
      public String getBar()
      {
        return bar;
      }
    
      public String getBaz()
      {
        return baz;
      }
      
      // this outputs all the data
      // except the baz String 
      public String showData()
      {
        return "foo is " + foo + ", bar is " + bar;
      }
      
    }
    MyChildClass.java
    Java Code:
    public class MyChildClass extends MyClass
    {
    
      public MyChildClass(int foo, String bar, String baz)
      {
        super(foo, bar, baz);
      }
    
      // uses the super method's result and adds baz data to it.
      public String showData()
      {
        return super.showData() + ", baz is " + super.getBaz();
      }
    
    }
    MainClass.java
    Java Code:
    public class MainClass
    {
      public static final String[] WORK_DAYS =
      {
        "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
      };
      public static final String[] RESPONSES =
      {
        "ugh", "keep going", "hump day", "can see the light", "party!"
      };
      
      public static void main(String[] args)
      {
        MyClass[] myClassArray = new MyClass[WORK_DAYS.length];
        for (int i = 0; i < myClassArray.length; i++)
        {
          myClassArray[i] = new MyChildClass(i, WORK_DAYS[i], RESPONSES[i]);
        }
        System.out.println("Show results:");
        for (MyClass anItem : myClassArray)
        {
          System.out.println(anItem.showData());
        }
      }
    }

  12. #12
    xf021209 is offline Member
    Join Date
    Mar 2009
    Posts
    12
    Rep Power
    0

    Default

    WOW, I didn't mean or expect you to go into such detail but the work and time you've spent helping me is GREATLY appreceated. This is great. I will be re-writing my project and will study what you'e provided. I wish my instructor could break code down into simple examples like you've provided. Thanks again, for all your work. This is great!

    Todd
    Last edited by xf021209; 04-20-2009 at 06:01 PM. Reason: dropped letter

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Glad it helped, and please let us know how the assignment goes.

Similar Threads

  1. Replies: 3
    Last Post: 01-29-2010, 07:53 AM
  2. [SOLVED] Array troubles, yes I searched...
    By Reiyn in forum New To Java
    Replies: 11
    Last Post: 04-17-2009, 12:28 AM
  3. StreamCorruptedException and Casting troubles
    By Wassa in forum Networking
    Replies: 2
    Last Post: 02-18-2009, 04:07 PM
  4. Subclass definition
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 09:03 PM
  5. subclass vs inner class
    By bugger in forum New To Java
    Replies: 1
    Last Post: 01-13-2008, 08:31 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •