Results 1 to 13 of 13
  1. #1
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Converting a static method to a non-static method

    The end of chapter exercise in my textbook gives the the following instructions:

    1. In the ProductDB class, modify the getProduct method so it's a regular method instead of a static method.

    2. In the ProductApp class, modify the code so it creates a ProductDB object named product. Then, use this object to call the getProduct method of the ProductDB class.

    Here's the code for the ProductDB class:
    Java Code:
    package SamProduct;
    
    public class ProductDB {
    
    	public Product getProduct(String nameOfItem){//non-static
    	//public static Product getProduct(String nameOfItem){//nameOfItem = user entry in ProductApp.java
    		//create the Product object:
    		Product product = new Product();
    		
    		//populate the product object with data:
    		if(nameOfItem.equalsIgnoreCase("java")){//java fills the name parameter in setItemName method
    			product.setItemName(nameOfItem);
    			product.setDescription("Java code, not the coffee drink.");
    			product.setPrice(12.34);
    		} else if(nameOfItem.equals("Fat Bastard")){
    			product.setItemName(nameOfItem);
    			product.setDescription("Baby-back, baby-back, I want my baby-back, baby-back!");
    			product.setPrice(25.00);
    		} else {
    			product.setDescription("No matches found for " + nameOfItem + "\n");
    		}
    		return product;
    	}
    }
    I'm not getting any errors for my change in the ProductDB's getProduct method, so step 1 appears to be a success.
    Now here is the code for the ProductApp class:
    Java Code:
    package SamProduct;
    import java.util.Scanner;
    
    public class ProductApp {
    
    	public static void main(String args[]){
    		System.out.println("Welcome to the product viewer.");
    		System.out.println();
    		
    		//create one or more line items:
    		Scanner sc = new Scanner(System.in);
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y")){
    			//get input from user:
    			System.out.print("Enter the name of the item you're searching for: ");
    			String nameOfItem = sc.nextLine();
    			
    			//Invoke method in ProductDB.java file to search for an item that matches 
    			//the user's input:
    			//Product product = ProductDB.getProduct(nameOfItem);//static method call
    			
    			Product product = getProduct(nameOfItem);//error: The method getProduct(String) 
    			//is undefined for the type ProductApp
    			
    			//Display the output of ProductDB.java file's search results:
    			String message = "\nPRODUCT\n" +
    					"Item:        " + product.getItemName() + "\n" +
    					"Description: " + product.getDescription() + "\n" +
    					"Price:       " + product.getPriceFormatted() + "\n";
    			System.out.println(message);
    			
    			//See if the user wants to continue:
    			System.out.print("Search for another item? (y/n): ");
    			choice = sc.nextLine();
    			System.out.println();
    		}//end of while loop
    		sc.close();
    		System.out.println("Goodbye!");
    	}//end of main method
    }//end of class body
    I'm not sure how to fix this, because the getProduct method is still public, even it's not static anymore. So what do I need to do to complete step 2?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Converting a static method to a non-static method

    Re-read part 2:

    In the ProductApp class, modify the code so it creates a ProductDB object named product. Then, use this object to call the getProduct method of the ProductDB class.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Converting a static method to a non-static method

    Quote Originally Posted by Tolls View Post
    Re-read part 2:

    In the ProductApp class, modify the code so it creates a ProductDB object named product. Then, use this object to call the getProduct method of the ProductDB class.
    I don't care if you think it looks like I'm asking to be spoon fed. I really need some syntax guidance here. I'm really confused:

    Java Code:
    //Invoke method in ProductDB.java file to search for an item that matches 
    			//the user's input:
    			//Product product = ProductDB.getProduct(nameOfItem);//static method call
    			
    			Product product = new ProductDB.getProduct();//ProductDB.getProduct cannot be resolved to a type
    			product = product.getProduct(nameOfItem);//The method getProduct(String) is undefined for the type Product
    It's not like it's out of scope either, because getProduct is public. What the hell does it want

  4. #4
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,995
    Rep Power
    9

    Default Re: Converting a static method to a non-static method

    Quote Originally Posted by Sam_JavaTheHut5580 View Post
    I don't care if you think it looks like I'm asking to be spoon fed. I really need some syntax guidance here. I'm really confused:

    Java Code:
    //Invoke method in ProductDB.java file to search for an item that matches 
    			//the user's input:
    			//Product product = ProductDB.getProduct(nameOfItem);//static method call
    			
    			Product product = new ProductDB.getProduct();//ProductDB.getProduct cannot be resolved to a type
    			product = product.getProduct(nameOfItem);//The method getProduct(String) is undefined for the type Product
    It's not like it's out of scope either, because getProduct is public. What the hell does it want

    You should carefully split the objects. You can say you need two instances: one of ProductDB and one of Product. Instantiate one of ProductDB and Product:
    Java Code:
    ProductDB db = new ProductDB();
    Product product = db.getProduct(...);
    Alternatively, and that's close to what you have, you can do it in one call, but that will have the disadvantage that you don't hold a reference to the db anymore. I would advise not to use this, until you fully understand how object creation and method chaining works.
    Java Code:
    Product product = new ProductDB().getProduct(...);
    Last edited by SurfMan; 06-07-2016 at 03:47 PM.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  5. #5
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Converting a static method to a non-static method

    Quote Originally Posted by SurfMan View Post
    You should carefully split the objects. You can say you need two instances: one of ProductDB and one of Product. Instantiate one of ProductDB and Product:
    Java Code:
    ProductDB db = new ProductDB();
    Product = db.getProduct(...);
    Well, the set methods are defined in the Product class, and called in the ProductDB class, so why doesn't it work:
    Java Code:
    //Invoke method in ProductDB.java file to search for an item that matches 
    			//the user's input:
    			//Product product = ProductDB.getProduct(nameOfItem);//static method call
    			Product = new ProductDB().getProduct(nameOfItem);//Product cannot be resolved to a variable
    			
    			ProductDB product = new ProductDB();
    			Product = product.getProduct(nameOfItem);//Product cannot be resolved to a variable

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Converting a static method to a non-static method

    Let's take step 2 a bit at a time then.

    "In the ProductApp class, modify the code so it creates a ProductDB object named product."

    (from the code posted by SurfMan)
    Java Code:
    ProductDB db = new ProductDB();
    'db' is now an instance of ProductDB.
    This means you can access non-static methods (instance methods) of ProductDB.
    Your getProduct() method is one such method.

    Then:
    (from your code earlier)
    Java Code:
    Product product = getProduct(nameOfItem);
    Now, obviously this doesn't work (you get a compilation error). The getProduct() method is not in the ProductApp class.
    So, re-reading the requirements, we see "(t)hen, use this object to call the getProduct method of the ProductDB class."

    We need to use the object ('db') that we just created to call getProduct().
    So just need to edit that line and so it uses db.getProduct(...).
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,995
    Rep Power
    9

    Default Re: Converting a static method to a non-static method

    Note that I have edited my code example due to a typo.... I accidently left out the variable name.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Converting a static method to a non-static method

    I took the liberty to illustrate some of the problems you have been having. I hope I
    haven't added to the confusion.

    Java Code:
    public class MethodLesson {
    
       public static void main(String[] args) {
          /**
           * To invoke instance methods you must qualify with them with their class
           * instance when:
           *     1. They are called from static contexts 
           *     2. They are in a different class.
           */
    
          start(); // error, main is static and start is instance (#1 above)
          MethodLesson ml = new MethodLesson();
          ml.start(); // correct! Method is qualified with ml instance.
       }
    
       public void start() {
          instanceMethod(); /**
                             * Correct! instanceMethod is in same class as start and
                             * start is also an instanceMethod. No qualification
                             * required.
                             */
          dcMethod(); /** Incorrect!  dcMethod is in different class.  Must
          be qualified with instance of DifferentClass. (#2 above)
          */
          DifferentClass dc = new DifferentClass();
          dc.dcMethod(); // Now correct
       }
    
       public void instanceMethod() {
          System.out.println("Instance method in same class");
       }
    }
    
    class DifferentClass {
       public void dcMethod() {
          System.out.println("instance method in Different Class");
       }
    }
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Converting a static method to a non-static method

    I just noticed I got something wrong up there.
    The step says:
    "so it creates a ProductDB object named product."
    So the bit I copied off SurfMan should actually be:
    Java Code:
    ProductDB product = new ProductDB();
    Not that I agree with that naming, but never mind, it's part of your exercise.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  10. #10
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: Converting a static method to a non-static method

    Quote Originally Posted by Tolls View Post
    I just noticed I got something wrong up there.
    The step says:
    "so it creates a ProductDB object named product."
    So the bit I copied off SurfMan should actually be:
    Java Code:
    ProductDB product = new ProductDB();
    Not that I agree with that naming, but never mind, it's part of your exercise.
    I'm going to come clean with you. Step 2 in the book actually said:

    2. In the ProductApp class, modify the code so it creates a ProductDB object named db. Then, use this object to call the getProduct method of the ProductDB class.

    I just don't understand the benefit of using a different variable name, because then you would have to alter all of the other instance calls for that object:
    Java Code:
    ProductDB db = new ProductDB();
    			db.getProduct(nameOfItem);//instance method call
    			
    			//Display the output of ProductDB.java file's search results:
    			String message = "\nPRODUCT\n" +
    					"Item:        " + db.getItemName() + "\n" + 
    					"Description: " + db.getDescription() + "\n" +
    					"Price:       " + db.getPriceFormatted() + "\n";
    			System.out.println(message);
    			
    			//Test the overloading of the 3 versions of the printToConsole method:
    			db.printToConsole();//no parameter version
    			db.printToConsole("|");
    			db.printToConsole("|", "Product: ");
    In addition to which, the getProduct method in the ProductDB class already creates an object with product as the variable name:
    Java Code:
    public class ProductDB {
    
    	public Product getProduct(String nameOfItem){//non-static
    	//public static Product getProduct(String nameOfItem){//nameOfItem = user entry in ProductApp.java
    		//create the Product object:
    		Product product = new Product();
    		
    		//populate the product object with data:
    		if(nameOfItem.equalsIgnoreCase("java")){//java fills the name parameter in setItemName method
    			product.setItemName(nameOfItem);
    			product.setDescription("Java code, not the coffee drink.");
    			product.setPrice(12.34);
    		} else {
    			product.setDescription("No matches found for " + nameOfItem + "\n");
    		}
    		return product;
    	}
    }
    Quote Originally Posted by jim829 View Post
    I took the liberty to illustrate some of the problems you have been having. I hope I
    haven't added to the confusion.
    No, your code in post #8 explained it quite well

    There's just a little more conflict left to deal with, because the Product class and its methods are not static:
    Java Code:
    //Invoke method in ProductDB.java file to search for an item that matches 
    			//the user's input:
    			//Product product = ProductDB.getProduct(nameOfItem);//static method call
    						
    			ProductDB product = new ProductDB();
    			product.getProduct(nameOfItem);//instance method call
    			
    			//Display the output of ProductDB.java file's search results:
    			String message = "\nPRODUCT\n" +
    					"Item:        " + product.getItemName() + "\n" + 
    					//error: The method getItemName() is undefined for the type ProductDB
    					"Description: " + Product.getDescription() + "\n" +
    					//error: Cannot make a static reference to the non-static method getDescription()
    					//from the type Product
    					"Price:       " + product.getPriceFormatted() + "\n";
    			System.out.println(message);
    More syntax guidance please.

    Also, I'm still struggling to understand the differences in scope for public and static methods.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Converting a static method to a non-static method

    the getProduct method in the ProductDB class already creates an object with product as the variable name:
    The variable: product in the getProduct method is local to that method. It does not exist outside of the method.
    The getProduct method returns a reference to an instance of a Product object. The code that calls that method NEEDs to save that reference in a variable so that it can be used to call the Product class's methods:
    Java Code:
      Product aProduct = db.getProduct(nameOfItem);//instance method call
    Then use the variable: aProduct to call the Product class's methods.
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Converting a static method to a non-static method

    Quote Originally Posted by Sam_JavaTheHut5580 View Post
    Also, I'm still struggling to understand the differences in scope for public and static methods.
    public and static are two different types of modifiers for methods, fields (and in some cases, classes).

    public, private, protected, and no-modifier are known as access modifiers. They have to do with the
    ability to access the classes and their internals.

    static vs non-static is simply declaring whether a variable or method requires an instance of a class to
    invoke or access the variable or method.
    Static means class methods or values.
    no static modifier means instance methods or values.

    The scope of a variable or method is different. It has to do with visibility of values or methods outside of
    where they are declared. Variables in methods have local scope to that method. Variables in blocks between
    {} have scope limited to those braces.

    Java Code:
          for (int j = 0; j < 10; j++) {
             int a;
             if (j == 5) {
                int b = j * 20;
                a = a * 10;
             }
             System.out.println(b); // outside of scope, declared in condition block
          }
          System.out.println(a); // outside of scope, declared in for block
    Read about access modifiers here -> Access modifiers
    I couldn't find anything in the tutorials on scope so here a section in the JLS. It is very verbose but it may help.
    Chapter*6.*Names

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Converting a static method to a non-static method

    Quote Originally Posted by Sam_JavaTheHut5580 View Post
    I'm going to come clean with you. Step 2 in the book actually said:

    2. In the ProductApp class, modify the code so it creates a ProductDB object named db. Then, use this object to call the getProduct method of the ProductDB class.

    I just don't understand the benefit of using a different variable name, because then you would have to alter all of the other instance calls for that object:
    Java Code:
    ProductDB db = new ProductDB();
    			db.getProduct(nameOfItem);//instance method call
    			
    			//Display the output of ProductDB.java file's search results:
    			String message = "\nPRODUCT\n" +
    					"Item:        " + db.getItemName() + "\n" + 
    					"Description: " + db.getDescription() + "\n" +
    					"Price:       " + db.getPriceFormatted() + "\n";
    			System.out.println(message);
    			
    			//Test the overloading of the 3 versions of the printToConsole method:
    			db.printToConsole();//no parameter version
    			db.printToConsole("|");
    			db.printToConsole("|", "Product: ");
    But the requirements say nothing about changing any other calls.
    ProductDB (from what I can see) simply handles (from the one method we can see) getting a Product out of some store (eg a database) based on its name.

    The rest of those methods belong with some other class. The getters should still be part of Product, and would be called based on the Product instance returned by the getProduct method. I'm assuming printToConsole will be wherever your main method sits (where does that method live at the moment, before the ProductDB stuff?).

    So, for example:
    Java Code:
    MyThing myThing = myThingStore.getMyThing("foo");
    System.out.println("MyThing is called - " + myThing.getName());
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Replies: 3
    Last Post: 05-31-2012, 07:56 PM
  2. Replies: 9
    Last Post: 06-10-2011, 12:40 AM
  3. Replies: 3
    Last Post: 02-09-2010, 05:22 AM
  4. Replies: 1
    Last Post: 02-10-2009, 10:03 AM
  5. Replies: 1
    Last Post: 08-07-2007, 05:05 AM

Posting Permissions

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