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

    Default How to dynamically work with inheritance

    I'm going through Chapter 11 (How To Work With Inheritance) in my text book. To deepen my understanding, I've created a BugShop application that has bugs up for sale, with Insects and Arachnids as my subclasses. When it comes to comparing objects, so far the book has explained the difference between comparing two objects and comparing the data of those two objects. But comparing two objects that are deliberately hard-coded in the main method together isn't going to teach me anything useful for the real world, so I want to go a little bit further. I'm trying to make it easy for the user to compare bug objects, but I'm struggling. As always, questions, errors messages, and explanations of my struggles are in my code comments. For the sake of space, I'm not going to include the two subclasses. Here goes:

    BugShop.java:
    Java Code:
    //super class
    package BugShop.business;
    import java.text.NumberFormat;
    
    public class BugShop {
    	private String BugID;
    	private String description;
    	private double price;
    	protected static int count = 0;//increments each time a new BugShop object is created
    	
    	public BugShop(){
    		this("", "", 0.0);
    	}
    	//overload constructor:
    	public BugShop(String BugID, String description, double price){
    		this.BugID = BugID;
    		this.description = description;
    		this.price = price;
    	}
    	
    	public void setBugID(String BugID){
    		this.BugID = BugID;
    	}
    	public String getBugID(){
    		return BugID;
    	}
    	public void setDescription(String description){
    		this.description = description;
    	}
    	public String getDescription(){
    		return description;
    	}
    	public void setPrice(double price){
    		this.price = price;
    	}
    	public double getPrice(){
    		return price;
    	}
    	public String getPriceFormatted(){
    		NumberFormat currency = NumberFormat.getCurrencyInstance();
    		String priceFormatted = currency.format(price);
    		return priceFormatted;
    	}
    	
    	@Override public String toString(){//overrides the toString method of the java.lang.Object class
    		return description;
    	}
    	
    	@Override public boolean objectsIdentical(BugShop bug){//error: The method objectsIdentical(BugShop) of type BugShop must override or implement a supertype method
    		
    		if(bug instanceof BugShop){//If the current BugShop object we're going to compare is a 
    			//bug instance from the BugShop superclass, 
    			BugShop currBug = (BugShop) bug;//then rename that object to currBug, so that we can 
    			//compare it as a separate object to one of the objects defined in the BugShopDB class.
    			
    			//Note that the user will have to choose which bugCode object to compare currBug to.			
    			//However, BugShopDB does not have any static methods. So how do I fix the comparison 
    			//statements below, so that they will compare the data of the current bug object with
    			//the data of the BugShopDB object chosen by the user?   
    			if(BugID.equals(currBug.getBugID()) &&
    				description.equals(currBug.getDescription()) &&
    				price == currBug.getPrice()){
    				return true;
    			}
    		}
    		return false;
    	}//end of objectsIdentical method
    	
    	public static int getCount(){//create public access for the count variable
    		return count;
    	}
    }
    BugShopDB.java:
    Java Code:
    package BugShop.db;
    
    import BugShop.business.*;
    
    public class BugShopDB {
    	//In the real world, I would use a database, but the book hasn't taught them yet, so we'll just
    	//use the objects hard-coded in here.
    	public BugShop getBug(String bugCode){
    		BugShop bug = null;
    		
    		if(bugCode.equalsIgnoreCase("Grasshopper")
    			|| bugCode.equalsIgnoreCase("Ant")
    			|| bugCode.equalsIgnoreCase("Aunt")){
    			Insects insect = new Insects();
    			
    			if(bugCode.equalsIgnoreCase("Grasshopper")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Hangs out in tall grass, sounds like a cricket.");
    				insect.setPrice(99.99);
    				insect.setInsectCategory("FlyingInsect");
    			}
    			else if(bugCode.equalsIgnoreCase("Ant")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Builds sand hills, and has 3 abdomens.");
    				insect.setPrice(8.99);
    				insect.setInsectCategory("GroundInsect");
    			}
    			//create an insect object to test the objectsIdentical method in the superclass:
    			else if(bugCode.equalsIgnoreCase("Aunt")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Builds sand hills, and has 3 abdomens.");
    				insect.setPrice(8.99);
    				insect.setInsectCategory("GroundInsect");
    			}
    			bug = insect;
    			
    		}else if(bugCode.equalsIgnoreCase("Tick")
    				|| bugCode.equalsIgnoreCase("Spider")
    				|| bugCode.equalsIgnoreCase("DeerTick")){
    			Arachnids arachnid = new Arachnids();
    			
    			if(bugCode.equalsIgnoreCase("Tick")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Latches itself to skin, and sucks blood. Carries diseases.");
    				arachnid.setPrice(5.99);
    				arachnid.setArachnidCategory("FlatBloodSucker");
    			}
    			else if(bugCode.equalsIgnoreCase("Spider")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Knits spider webs to trap insects and suck their guts out.");
    				arachnid.setPrice(52.33);
    				arachnid.setArachnidCategory("8LeggedFreaks");
    			}
    			//create an arachnid object to test the objectsIdentical method in the superclass:
    			else if(bugCode.equalsIgnoreCase("DeerTick")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Latches itself to skin, and sucks blood. Carries diseases.");
    				arachnid.setPrice(5.99);
    				arachnid.setArachnidCategory("FlatBloodSucker");
    			}
    			bug = arachnid;
    		}
    		return bug;
    	}//end of getBug method
    }
    BugShopApp.java:
    Java Code:
    package BugShop.ui;
    import BugShop.business.BugShop;
    import BugShop.db.BugShopDB;
    import java.util.Scanner;
    
    public class BugShopApp {
    	public static void main(String args[]){
    		//display welcome message
    		System.out.println("Welome to the BugShop");
    		System.out.println();
    		
    		//prompt user for bug code
    		Scanner sc = new Scanner(System.in);
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y")){
    			System.out.println("Enter bug code:");
    			String bugCode = sc.nextLine();
    			
    			BugShopDB db = new BugShopDB();
    			BugShop bug = db.getBug(bugCode);
    			String currBug = bugCode;			
    			
    			if(bug != null){
    				System.out.println("Description: " + bug.toString());
    				System.out.println("Price: " + bug.getPriceFormatted());
    			}else{
    				System.out.println("Sorry, this bug wasn't found in the BugShop.");
    			}
    			
    			System.out.println("Do you wish to find out if there are any other bugs with the exact "
    					+ "same data (y/n)?");
    			Scanner sameBug = new Scanner(System.in);
    			String choiceToCompare = sameBug.nextLine();
    			if(choiceToCompare.equalsIgnoreCase("y")){		
    				System.out.println("The bugCodes you can compare " + currBug + " to are:");
    				//Iterate through the getBug method in BugShopDB, and list all existing bugCodes:
    				for(int i = 0; i < ?; i++){
    					System.out.println(bugCode);
    				}
    				BugShop objectsIdentical(bug);//error: Syntax error on token "objectsIdentical", = expected after this token
    			}			
    					
    			System.out.println("Continue? (y/n)");
    			choice = sc.nextLine();
    			System.out.println();
    		}
    		sc.close();
    		System.out.println("Bye!");
    	}
    }

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

    Default Re: How to dynamically work with inheritance

    A couple of things.

    1. Some of your error messages are off the screen so I can't read them.

    2. What is BugShop? If it is a super class of a particular bug then it should probably be just called Bug.
    After all, a cat or a dog is not a type of PetShop. When subclassing use the is-a test. Is the subclass
    a special type of the superclass? If not, the hierarchical naming is not correct.

    3. It looks like you have an ObjectsIdentical method for determining if the bugs are the same. That's fine for
    practice but you should read about overriding equals and hashCode. Equals probably offers the same capability and hashCode
    will be important when you want to add your objects to Maps (e.g. HashMap).

    4. Why the question mark in line 37 of BugShopApp?

    5. Line 40 in BugShopApp doesn't make sense. And it is syntactically incorrect (what was your intent).

    6. You should probably show a few of the bug subclasses. Otherwise there may be related errors that we can't
    help you with.

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

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

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by jim829 View Post
    What is BugShop? If it is a super class of a particular bug then it should probably be just called Bug.
    Yeah I know. I already thought of that long after I started this project, and long before I made this post, but I'll worry about changing that later.
    Quote Originally Posted by jim829 View Post
    Why the question mark in line 37 of BugShopApp?
    I was going to try and figure out how to iterate through BugShopDB and collect all of the bugCode strings to list them to make it more likely for the user to enter a valid bugCode to compare with, but it's much easier to just give them to the user:
    Java Code:
    System.out.println("The bugs you can compare a " + currBug + "'s data to are:");
    				System.out.println("Grasshopper, Ant, Aunt, Tick, Spider, or DeerTick.");
    Quote Originally Posted by jim829 View Post
    Line 40 in BugShopApp doesn't make sense. And it is syntactically incorrect (what was your intent).
    See for yourself in the comments on lines 49 and 50 in the new code. Of course, now I have a new problem on the 7 lines before that. I can't compare the bugCode strings with the bugToCompareTo variable entered by the user, because an object and a string are not the same. Is there a way to convert an object name to a string, so I can compare the bugCode object names as strings?
    Quote Originally Posted by jim829 View Post
    You should probably show a few of the bug subclasses. Otherwise there may be related errors that we can't
    help you with.
    I can feel the pain of the forum table's stretch marks already

    One other thing. How come commenting out the @Override on line 49 in BugShop.java made the error go away?

    BugShopApp.java:
    Java Code:
    package BugShop.ui;
    import BugShop.business.BugShop;
    import BugShop.db.BugShopDB;
    import java.util.Scanner;
    
    public class BugShopApp {
    	public static void main(String args[]){
    		//display welcome message
    		System.out.println("Welome to the BugShop");
    		System.out.println();
    		
    		//prompt user for bug code
    		Scanner sc = new Scanner(System.in);
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y")){
    			System.out.println("Enter bug code:");
    			String bugCode = sc.nextLine();
    			
    			BugShopDB db = new BugShopDB();
    			BugShop bug = db.getBug(bugCode);
    			String currBug = bugCode;			
    			
    			if(bug != null){
    				System.out.println("Description: " + bug.toString());
    				System.out.println("Price: " + bug.getPriceFormatted());
    			}else{
    				System.out.println("Sorry, this bug wasn't found in the BugShop.");
    			}
    			
    			System.out.println("Do you wish to find out if there are any other bugs with the exact "
    					+ "same data (y/n)?");
    			Scanner cmpBug = new Scanner(System.in);
    			String choiceToCompare = cmpBug.nextLine();
    			if(choiceToCompare.equalsIgnoreCase("y")){		
    				System.out.println("The bugs you can compare a " + currBug + "'s data to are:");
    				System.out.println("Grasshopper, Ant, Aunt, Tick, Spider, or DeerTick.");
    				
    				Scanner compare = new Scanner(System.in);
    				String bugToCompareTo = compare.nextLine();
    				
    				BugShopDB db2 = new BugShopDB();
    				BugShop bug2 = db2.getBug(bugToCompareTo);				
    				
    				if(bugToCompareTo.equalsIgnoreCase("Grasshopper") ||
    					bugToCompareTo.equalsIgnoreCase("Ant") ||
    					bugToCompareTo.equalsIgnoreCase("Aunt") ||
    					bugToCompareTo.equalsIgnoreCase("Tick") ||
    					bugToCompareTo.equalsIgnoreCase("Spider") ||
    					bugToCompareTo.equalsIgnoreCase("DeerTick")){
    					//if the bugToCompareTo matches a bugCode in BugShopDB, then execute the 
    					//objectsDataIdentical method to find out if their data matches:
    					
    					BugShop objectsDataIdentical = (bug);
    					if (bug.equals(bug2)) {
    			            System.out.println("Yep, that's the same bug!");
    			        } else {
    			            System.out.println("No, some of that bug's features are different than " 
    			        + currBug);
    			        }
    				}	
    			}			
    					
    			System.out.println("Continue? (y/n)");
    			choice = sc.nextLine();
    			System.out.println();
    		}
    		sc.close();
    		System.out.println("Bye!");
    	}
    }
    BugShop.java:
    Java Code:
    //super class
    package BugShop.business;
    import java.text.NumberFormat;
    
    public class BugShop {
    	private String BugID;
    	private String description;
    	private double price;
    	protected static int count = 0;//increments each time a new BugShop object is created
    	
    	public BugShop(){
    		this("", "", 0.0);
    	}
    	//overload constructor:
    	public BugShop(String BugID, String description, double price){
    		this.BugID = BugID;
    		this.description = description;
    		this.price = price;
    	}
    	
    	public void setBugID(String BugID){
    		this.BugID = BugID;
    	}
    	public String getBugID(){
    		return BugID;
    	}
    	public void setDescription(String description){
    		this.description = description;
    	}
    	public String getDescription(){
    		return description;
    	}
    	public void setPrice(double price){
    		this.price = price;
    	}
    	public double getPrice(){
    		return price;
    	}
    	public String getPriceFormatted(){
    		NumberFormat currency = NumberFormat.getCurrencyInstance();
    		String priceFormatted = currency.format(price);
    		return priceFormatted;
    	}
    	
    	@Override public String toString(){//overrides the toString method of the java.lang.Object class
    		return description;
    	}
    	
    	@Override 
    	public boolean objectsDataIdentical(BugShop bug){//error: The method objectsDataIdentical(BugShop)
    		//of type BugShop must override or implement a supertype method
    		
    		if(bug instanceof BugShop){//If the current BugShop object is an instance from the BugShop
    			//superclass, 
    			BugShop currBug = (BugShop) bug;//then rename that object to currBug, so that we can 
    			//compare it as a separate object to one of the objects defined in the BugShopDB class.
    			   
    			if(BugID.equals(currBug.getBugID()) &&
    				description.equals(currBug.getDescription()) &&
    				price == currBug.getPrice()){
    				return true;
    			}
    		}
    		return false;
    	}//end of objectsDataIdentical method
    	
    	public static int getCount(){//create public access for the count variable
    		return count;
    	}
    	
    	//public abstract String getDisplayText();//an abstract method (defined and used by sub classes only)
    }
    Insects.java:
    Java Code:
    //subclass
    package BugShop.business;
    
    public class Insects extends BugShop {
    	private String insectCategory;
    	
    	public Insects(){
    		super();//call constructor of BugShop super class
    		insectCategory = "";
    		count++;
    	}
    	//overload constructor:
    	public Insects(String insectCategory){
    		this.insectCategory = insectCategory;
    	}
    	
    	public void setInsectCategory(String insectCategory){
    		this.insectCategory = insectCategory;
    	}
    	public String getInsectCategory(){
    		return insectCategory;
    	}
    	
    	@Override public String toString(){//override the toString method
    		return super.toString() +
    				" the insect is a " + insectCategory;//examples: beetle, ant, fly, bee, any 6-legged
    	}
    	/*
    	@Override public String getDisplayText(){//implement the superclass's abstract method
    		return super.toString() +
    				" the insect is a " + insectCategory;//examples: beetle, ant, fly, bee, any 6-legged"
    	}
    	*/
    	@Override public boolean objectsDataIdentical(BugShop bug){//Override the equals method
    		return super.equals(bug);
    	}
    }//end of class
    Arachnids.java:
    Java Code:
    //subclass
    package BugShop.business;
    
    public class Arachnids extends BugShop {
    	private String arachnidCategory;
    	
    	public Arachnids(){
    		super();
    		arachnidCategory = "";
    		count++;
    	}
    	//overload constructor:
    	public Arachnids(String arachnidCategory){
    		this.arachnidCategory = arachnidCategory;
    	}
    	public void setArachnidCategory(String arachnidCategory){
    		this.arachnidCategory = arachnidCategory;
    	}
    	public String getArachnidCategory(){
    		return arachnidCategory;
    	}
    	
    	@Override public String toString(){
    		return super.toString() +
    				" the arachnid is a " + arachnidCategory;//examples: spider, tick, scorpion, mite, any 8-legged 
    	}
    	/*
    	@Override public String getDisplayText(){//implement the superclass's abstract method
    		return super.toString() +
    				" the arachnid is a " + arachnidCategory;//examples: spider, tick, scorpion, mite, any 8-legged
    	}
    	*/
    	@Override public boolean objectsDataIdentical(BugShop bug){//Override the equals method
    		return super.equals(bug);
    	}
    }//end of class
    BugShopDB.java:
    Java Code:
    package BugShop.db;
    
    import BugShop.business.*;
    
    public class BugShopDB {
    	//In the real world, I would use a database, but the book hasn't taught them yet, so we'll just
    	//use the objects hard-coded in here.
    	public BugShop getBug(String bugCode){
    		BugShop bug = null;
    		
    		if(bugCode.equalsIgnoreCase("Grasshopper")
    			|| bugCode.equalsIgnoreCase("Ant")
    			|| bugCode.equalsIgnoreCase("Aunt")){
    			Insects insect = new Insects();
    			
    			if(bugCode.equalsIgnoreCase("Grasshopper")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Hangs out in tall grass, sounds like a cricket.");
    				insect.setPrice(99.99);
    				insect.setInsectCategory("FlyingInsect");
    			}
    			else if(bugCode.equalsIgnoreCase("Ant")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Builds sand hills, and has 3 abdomens.");
    				insect.setPrice(8.99);
    				insect.setInsectCategory("GroundInsect");
    			}
    			//create an insect object to test the objectsDataIdentical method in the superclass:
    			else if(bugCode.equalsIgnoreCase("Aunt")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Builds sand hills, and has 3 abdomens.");
    				insect.setPrice(8.99);
    				insect.setInsectCategory("GroundInsect");
    			}
    			bug = insect;
    			
    		}else if(bugCode.equalsIgnoreCase("Tick")
    				|| bugCode.equalsIgnoreCase("Spider")
    				|| bugCode.equalsIgnoreCase("DeerTick")){
    			Arachnids arachnid = new Arachnids();
    			
    			if(bugCode.equalsIgnoreCase("Tick")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Latches itself to skin, and sucks blood. Carries diseases.");
    				arachnid.setPrice(5.99);
    				arachnid.setArachnidCategory("FlatBloodSucker");
    			}
    			else if(bugCode.equalsIgnoreCase("Spider")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Knits spider webs to trap insects and suck their guts out.");
    				arachnid.setPrice(52.33);
    				arachnid.setArachnidCategory("8LeggedFreaks");
    			}
    			//create an arachnid object to test the objectsDataIdentical method in the superclass:
    			else if(bugCode.equalsIgnoreCase("DeerTick")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Latches itself to skin, and sucks blood. Carries diseases.");
    				arachnid.setPrice(5.99);
    				arachnid.setArachnidCategory("FlatBloodSucker");
    			}
    			bug = arachnid;
    		}
    		return bug;
    	}//end of getBug method
    }
    Last edited by Sam_JavaTheHut5580; 08-10-2016 at 09:41 PM.

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

    Default Re: How to dynamically work with inheritance

    One other thing. How come commenting out the @Override on line 49 in BugShop.java made the error go away?
    Because the annotation is used as a safety net to help override methods correctly (especially with interfaces).
    If you don't override an existing method signature correctly (method name and arguments) the compiler complains. If
    you remove the @Override, the compiler just assumes you are creating a new method so there is nothing
    to complain about.

    But it also means that if you did mean to override a method, it probably won't work as expected so you should put
    the @Override back and then fix the real problem.

    You seem to not fully understand the purpose of inheritance. Among other things, it is there to save you time and provide for code re-use.
    So why to do you have separate categories and other characteristics for each of your bug subclasses when you have
    the inherited version of them in your base class? Just use the ones in the base class. Only unique methods and data
    need to be added to the subclasses.

    Java Code:
    class Bug {
        private int eyeCount;
        private int weight;
        private boolean hasWings;
        private int category;
        private boolean isDangerous;
        // now add getters and setters for those values;
        public void setEyeCount(int eyeCount) {
            this.eyeCount = eyeCount;
        }
        public int getEyeCount() {
            return eyeCount();
        }
        // etc
    }
    
    
    // only add new methods to the following sub classes
    public class Spider extends Bug{}
    public class Tick extends Bug{};
    Regards,
    Jim
    Last edited by jim829; 08-10-2016 at 04:41 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

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

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by jim829 View Post
    But it also means that if you did mean to override a method, it probably won't work as expected so you should put
    the @Override back and then fix the real problem.
    I thought so, but I don't understand what the problem is, because even though the method is being defined in the superclass, the error still says:

    "The method objectsDataIdentical(BugShop) of type BugShop must override or implement a supertype method" [BugShop.java, line 50 after uncommenting line 49]

    So why is it looking for a supertype method?

    Quote Originally Posted by jim829 View Post
    You seem to not fully understand the purpose of inheritance. Among other things, it is there to save you time and provide for code re-use.
    What do you mean? If you recall, I called the superclass constructor in the default constructor of my subclasses. For example:
    Java Code:
    public Insects(){
            super();//call constructor of BugShop super class
            insectCategory = "";
            count++;
        }
    Isn't that code re-use?

    Quote Originally Posted by jim829 View Post
    So why to do you have separate categories and other characteristics for each of your bug subclasses when you have
    the inherited version of them in your base class?
    The book was trying to teach the basics of overriding superclass methods in a subclass. I guess appending another string to the description string from the superclass was the simplest method overriding example that Murach could come up with for working with inheritance.

    Also, you didn't answer my question regarding lines 42 through 48 in BugShopApp.java. I can't compare the bugCode strings with the bugToCompareTo variable entered by the user, because an object and a string are not the same. Is there a way to convert an object name to a string, so I can compare the bugCode object names as strings?

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

    Default Re: How to dynamically work with inheritance

    In those lines you have objectsIdentical. Elsewhere you have objectsDataIdentical. Not certain if they are meant to be the same or not. When you
    say Object name, what are you talking about. The java class or some name string in your code?

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

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

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by jim829 View Post
    In those lines you have objectsIdentical. Elsewhere you have objectsDataIdentical. Not certain if they are meant to be the same or not.
    The method is supposed to be named objectsDataIdentical in all of the classes. Make sure you refer to my code in post #3, NOT post #1.

    Quote Originally Posted by jim829 View Post
    When you say Object name, what are you talking about. The java class or some name string in your code?
    My bad. I forgot to pass in the bugToCompareTo string as the bugCode argument for the bug2 object instantiation statement on line 42 in the updated BugShopApp.java class. I'm also not sure if the method call on line 53 is correct either, but we won't be able to test the code to find out until we fix the error on line 50 in the BugShop.java class. (see post #3, I've just updated the code there).

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

    Default Re: How to dynamically work with inheritance

    Upon further examination your statements:

    Java Code:
    @Override    
    public boolean objectsDataIdentical(BugShop bug)
    {
    //error: The method objectsDataIdentical(BugShop)
            //of type BugShop must override or implement a supertype method
    }
    don't make sense since BugShop doesn't implement an interface or extend a class. So there is nothing to override.
    To ensure that you can compare whether one BugShop object equals another you should override the equals method (which
    is inherited from the Object 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
    Join Date
    Mar 2016
    Posts
    93
    Rep Power
    0

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by jim829 View Post
    To ensure that you can compare whether one BugShop object equals another you should override the equals method (which
    is inherited from the Object class).
    Done. Unfortunately though, test failed
    How to dynamically work with inheritance-bugshoptestfailed.png
    Not true. If you look at BugShopDB.java, Both Ant and Aunt have identical data. Tick and DeerTick also both have identical data There are only two things I can think of:

    1.) The program somehow compared the objects themselves instead of the data in the objects.
    2.) The java utility scanner had a resource leak on lines 32 and 38 in BugShopApp.java.

    Which one do you think it is?:

    BugShop.java:
    Java Code:
    //super class
    package BugShop.business;
    import java.text.NumberFormat;
    
    public class BugShop {
    	private String BugID;
    	private String description;
    	private double price;
    	protected static int count = 0;//increments each time a new BugShop object is created
    	
    	public BugShop(){
    		this("", "", 0.0);
    	}
    	//overload constructor:
    	public BugShop(String BugID, String description, double price){
    		this.BugID = BugID;
    		this.description = description;
    		this.price = price;
    	}
    	
    	public void setBugID(String BugID){
    		this.BugID = BugID;
    	}
    	public String getBugID(){
    		return BugID;
    	}
    	public void setDescription(String description){
    		this.description = description;
    	}
    	public String getDescription(){
    		return description;
    	}
    	public void setPrice(double price){
    		this.price = price;
    	}
    	public double getPrice(){
    		return price;
    	}
    	public String getPriceFormatted(){
    		NumberFormat currency = NumberFormat.getCurrencyInstance();
    		String priceFormatted = currency.format(price);
    		return priceFormatted;
    	}
    	
    	@Override 
    	public String toString(){//overrides the toString method of the java.lang.Object class
    		return description;
    	}
    	
    	@Override 
    	public boolean equals(Object object){//overrides the equals method of the java.lang.Object class
    		
    		if(object instanceof BugShop){//If the current BugShop object is an instance from the BugShop
    			//superclass, 
    			BugShop bug2 = (BugShop) object;//then rename that object to currBug, so that we can 
    			//compare it as a separate object to one of the objects defined in the BugShopDB class.
    			   
    			if(BugID.equals(bug2.getBugID()) &&
    				description.equals(bug2.getDescription()) &&
    				price == bug2.getPrice()){
    				return true;
    			}
    		}
    		return false;
    	}//end of equals method
    	
    	public static int getCount(){//create public access for the count variable
    		return count;
    	}
    }
    BugShopApp.java:
    Java Code:
    package BugShop.ui;
    import BugShop.business.BugShop;
    import BugShop.db.BugShopDB;
    import java.util.Scanner;
    
    public class BugShopApp {
    	public static void main(String args[]){
    		//display welcome message
    		System.out.println("Welome to the BugShop");
    		System.out.println();
    		
    		//prompt user for bug code
    		Scanner sc = new Scanner(System.in);
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y")){
    			System.out.println("Enter bug code:");
    			String bugCode = sc.nextLine();
    			
    			BugShopDB db = new BugShopDB();
    			BugShop bug = db.getBug(bugCode);
    			String currBug = bugCode;			
    			
    			if(bug != null){
    				System.out.println("Description: " + bug.toString());
    				System.out.println("Price: " + bug.getPriceFormatted());
    			}else{
    				System.out.println("Sorry, this bug wasn't found in the BugShop.");
    			}
    			
    			System.out.println("Do you wish to find out if there are any other bugs with the exact "
    					+ "same data (y/n)?");
    			Scanner cmpBug = new Scanner(System.in);
    			String choiceToCompare = cmpBug.nextLine();
    			if(choiceToCompare.equalsIgnoreCase("y")){		
    				System.out.println("The bugs you can compare a " + currBug + "'s data to are:");
    				System.out.println("Grasshopper, Ant, Aunt, Tick, Spider, or DeerTick.");
    				
    				Scanner compare = new Scanner(System.in);
    				String bugToCompareTo = compare.nextLine();
    				
    				BugShopDB db2 = new BugShopDB();
    				BugShop bug2 = db2.getBug(bugToCompareTo);				
    				
    				if(bugToCompareTo.equalsIgnoreCase("Grasshopper") ||
    					bugToCompareTo.equalsIgnoreCase("Ant") ||
    					bugToCompareTo.equalsIgnoreCase("Aunt") ||
    					bugToCompareTo.equalsIgnoreCase("Tick") ||
    					bugToCompareTo.equalsIgnoreCase("Spider") ||
    					bugToCompareTo.equalsIgnoreCase("DeerTick")){
    					//if the bugToCompareTo matches a bugCode in BugShopDB, then execute the 
    					//objectsDataIdentical method to find out if their data matches:
    					
    					BugShop objectsDataIdentical = (bug);
    					if (bug.equals(bug2)) {
    			            System.out.println("Yep, that's the same bug!");
    			        } else {
    			            System.out.println("No, some of that bug's features are different than " 
    			        + currBug);
    			        }
    				}	
    			}			
    					
    			System.out.println("Continue? (y/n)");
    			choice = sc.nextLine();
    			System.out.println();
    		}
    		sc.close();
    		System.out.println("Bye!");
    	}
    }
    Insects.java:
    Java Code:
    //subclass
    package BugShop.business;
    
    public class Insects extends BugShop {
    	private String insectCategory;
    	
    	public Insects(){
    		super();//call constructor of BugShop super class
    		insectCategory = "";
    		count++;
    	}
    	//overload constructor:
    	public Insects(String insectCategory){
    		this.insectCategory = insectCategory;
    	}
    	
    	public void setInsectCategory(String insectCategory){
    		this.insectCategory = insectCategory;
    	}
    	public String getInsectCategory(){
    		return insectCategory;
    	}
    	
    	@Override public String toString(){//override the toString method
    		return super.toString() +
    				" the insect is a " + insectCategory;//examples: beetle, ant, fly, bee, any 6-legged
    	}
    	@Override public boolean equals(Object bug){//Override the equals method
    		return super.equals(bug);
    	}
    }//end of class
    Arachnids.java:
    Java Code:
    //subclass
    package BugShop.business;
    
    public class Arachnids extends BugShop {
    	private String arachnidCategory;
    	
    	public Arachnids(){
    		super();
    		arachnidCategory = "";
    		count++;
    	}
    	//overload constructor:
    	public Arachnids(String arachnidCategory){
    		this.arachnidCategory = arachnidCategory;
    	}
    	public void setArachnidCategory(String arachnidCategory){
    		this.arachnidCategory = arachnidCategory;
    	}
    	public String getArachnidCategory(){
    		return arachnidCategory;
    	}
    	
    	@Override public String toString(){
    		return super.toString() +
    				" the arachnid is a " + arachnidCategory;//examples: spider, tick, scorpion, mite, any 8-legged 
    	}
    	
    	@Override public boolean equals(Object bug){//Override the equals method
    		return super.equals(bug);
    	}
    }//end of class
    BugShopDB.java:
    Java Code:
    package BugShop.db;
    
    import BugShop.business.*;
    
    public class BugShopDB {
    	//In the real world, I would use a database, but the book hasn't taught them yet, so we'll just
    	//use the objects hard-coded in here.
    	public BugShop getBug(String bugCode){
    		BugShop bug = null;
    		
    		if(bugCode.equalsIgnoreCase("Grasshopper")
    			|| bugCode.equalsIgnoreCase("Ant")
    			|| bugCode.equalsIgnoreCase("Aunt")){
    			Insects insect = new Insects();
    			
    			if(bugCode.equalsIgnoreCase("Grasshopper")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Hangs out in tall grass, sounds like a cricket.");
    				insect.setPrice(99.99);
    				insect.setInsectCategory("FlyingInsect");
    			}
    			else if(bugCode.equalsIgnoreCase("Ant")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Builds sand hills, and has 3 abdomens.");
    				insect.setPrice(8.99);
    				insect.setInsectCategory("GroundInsect");
    			}
    			//create an insect object to test the objectsDataIdentical method in the superclass:
    			else if(bugCode.equalsIgnoreCase("Aunt")){
    				insect.setBugID(bugCode);
    				insect.setDescription("Builds sand hills, and has 3 abdomens.");
    				insect.setPrice(8.99);
    				insect.setInsectCategory("GroundInsect");
    			}
    			bug = insect;
    			
    		}else if(bugCode.equalsIgnoreCase("Tick")
    				|| bugCode.equalsIgnoreCase("Spider")
    				|| bugCode.equalsIgnoreCase("DeerTick")){
    			Arachnids arachnid = new Arachnids();
    			
    			if(bugCode.equalsIgnoreCase("Tick")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Latches itself to skin, and sucks blood. Carries diseases.");
    				arachnid.setPrice(5.99);
    				arachnid.setArachnidCategory("FlatBloodSucker");
    			}
    			else if(bugCode.equalsIgnoreCase("Spider")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Knits spider webs to trap insects and suck their guts out.");
    				arachnid.setPrice(52.33);
    				arachnid.setArachnidCategory("8LeggedFreaks");
    			}
    			//create an arachnid object to test the objectsDataIdentical method in the superclass:
    			else if(bugCode.equalsIgnoreCase("DeerTick")){
    				arachnid.setBugID(bugCode);
    				arachnid.setDescription("Latches itself to skin, and sucks blood. Carries diseases.");
    				arachnid.setPrice(5.99);
    				arachnid.setArachnidCategory("FlatBloodSucker");
    			}
    			bug = arachnid;
    		}
    		return bug;
    	}//end of getBug method
    }
    Last edited by Sam_JavaTheHut5580; 08-11-2016 at 01:38 AM.

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

    Default Re: How to dynamically work with inheritance

    Instead of looking at the DB, I would recommend you put print statements in the equals method to print the values you are comparing.
    Then you can be certain you are comparing identical values. And I also recommend that when you print strings, you put them between
    something like quotes. This way, you can visually detect trailing or leading spaces which can affect the comparison.

    But it looks like you implemented the equals method perfectly!

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

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

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by jim829 View Post
    Instead of looking at the DB, I would recommend you put print statements in the equals method to print the values you are comparing. Then you can be certain you are comparing identical values.
    Well, I tried that:
    Java Code:
    @Override 
    	public boolean equals(Object object){//overrides the equals method of the java.lang.Object class
    		
    		if(object instanceof BugShop){//If the current BugShop object is an instance from the BugShop
    			//superclass, 
    			BugShop bug2 = (BugShop) object;//then rename that object to currBug, so that we can 
    			//compare it as a separate object to one of the objects defined in the BugShopDB class.
    			   
    			if(BugID.equals(bug2.getBugID()) &&
    				description.equals(bug2.getDescription()) &&
    				price == bug2.getPrice()){
    				System.out.println("Yes, the bugs do share the same data.");
    				return true;
    			}
    		}
    		System.out.println("No, the bugs do not share the same data.");
    		return false;
    	}//end of equals method
    but it didn't print any statements:
    How to dynamically work with inheritance-bugshoptestfailed2.png

    Quote Originally Posted by jim829 View Post
    And I also recommend that when you print strings, you put them between something like quotes. This way, you can visually detect trailing or leading spaces which can affect the comparison.
    What part of my code in post #9 are you suggesting this for?

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

    Default Re: How to dynamically work with inheritance

    Within the equals method after you determine the correct object type, simply print out
    bugID, price, and description from both objects to see if they should be equal or not.

    Sprinkling print statements throughout your code to help verify programming logic, is probably
    the most often used debugging tool by programmers.

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

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

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by jim829 View Post
    Within the equals method after you determine the correct object type, simply print out
    bugID, price, and description from both objects to see if they should be equal or not.
    Gladly, but first we have to fix the error preventing us from accessing the equals method on line 56 in BugShopApp.java:
    Java Code:
    package BugShop.ui;
    import BugShop.business.BugShop;
    import BugShop.db.BugShopDB;
    import SamPokemon.business.Pokemon;
    import SamPokemon.db.PokemonDB;
    
    import java.util.Scanner;
    
    public class BugShopApp {
    	public static void main(String args[]){
    		//display welcome message
    		System.out.println("Welome to the BugShop");
    		System.out.println();
    		
    		//prompt user for bug code
    		Scanner sc = new Scanner(System.in);
    		String choice = "y";
    		while(choice.equalsIgnoreCase("y")){
    			System.out.println("Enter bug code:");
    			String bugCode = sc.nextLine();
    			
    			BugShopDB db = new BugShopDB();
    			BugShop bug = db.getBug(bugCode);
    			String currBug = bugCode;			
    			
    			if(bug != null){
    				System.out.println("Description: " + bug.toString());
    				System.out.println("Price: " + bug.getPriceFormatted());
    			}else{
    				System.out.println("Sorry, this bug wasn't found in the BugShop.");
    			}
    			
    			System.out.println("Do you wish to find out if there are any other bugs with the exact "
    					+ "same data (y/n)?");
    			Scanner cmpBug = new Scanner(System.in);
    			String choiceToCompare = cmpBug.nextLine();
    			if(choiceToCompare.equalsIgnoreCase("y")){		
    				System.out.println("The bugs you can compare a " + currBug + "'s data to are:");
    				System.out.println("Grasshopper, Ant, Aunt, Tick, Spider, or DeerTick.");
    				
    				Scanner compare = new Scanner(System.in);
    				String bugToCompareTo = compare.nextLine();
    				
    				BugShopDB db2 = new BugShopDB();
    				BugShop bug2 = db2.getBug(bugToCompareTo);				
    				
    				if(bugToCompareTo.equalsIgnoreCase("Grasshopper") ||
    					bugToCompareTo.equalsIgnoreCase("Ant") ||
    					bugToCompareTo.equalsIgnoreCase("Aunt") ||
    					bugToCompareTo.equalsIgnoreCase("Tick") ||
    					bugToCompareTo.equalsIgnoreCase("Spider") ||
    					bugToCompareTo.equalsIgnoreCase("DeerTick")){
    					//if the bugToCompareTo matches a bugCode in BugShopDB, then execute the 
    					//equals method to find out if their data matches:
    										
    					BugShop.equals(bug);//error: Cannot make a static reference to the non-static 
    					//method equals(Object) from the type BugShop
    					/*
    					BugShop equals = (bug);
    					if (bug.equals(bug2)) {
    			            System.out.println("Yep, that's the same bug!");
    			        } else {
    			            System.out.println("No, some of that bug's features are different than " 
    			        + currBug);
    			        }
    			        */
    				}	
    			}			
    					
    			System.out.println("Continue? (y/n)");
    			choice = sc.nextLine();
    			System.out.println();
    		}
    		sc.close();
    		System.out.println("Bye!");
    	}
    }
    In the past, I have recorded the difference between static and instance method calls for creating an object. For example:
    Java Code:
    //get the Pokemon object:
    //Pokemon pokemon = PokemonDB.getPokemon(whoIsThatPokemon);//static method call
    			
    PokemonDB db = new PokemonDB();
    Pokemon pokemon = db.getPokemon(whoIsThatPokemon);//instance method call
    But this time, I'm trying to compare two the data of two objects (that have already been instantiated, bug on lines 22 - 23, and bug2 on lines 44 - 45 of the BugShopApp.java code above).

    You've said in another post that comparing static and public doesn't make sense, but I disagree. The scope of the two seems so similar to me. The equals method in BugShop.java is public:
    Java Code:
    @Override 
    	public boolean equals(Object object){//overrides the equals method of the java.lang.Object class
    		
    		if(object instanceof BugShop){//If the current BugShop object is an instance from the BugShop
    			//superclass, 
    			BugShop bug2 = (BugShop) object;//then rename that object to bug2, so that we can 
    			//compare it as a separate object to one of the objects defined in the BugShopDB class.
    			
    			//simply print out bugID, price, and description from both objects 
    			//to see if they should be equal or not:
    			System.out.println(BugID + ", " + description + ", " + price);//for bug
    			System.out.println(bug2.getBugID() + ", " + bug2.getDescription() + ", " 
    			+ bug2.getPrice());//for bug2
    			   
    			if(BugID.equals(bug2.getBugID()) && //if bug and bug2 have same BugID
    				description.equals(bug2.getDescription()) &&
    				price == bug2.getPrice()){
    				
    				return true;
    			}
    		}
    		System.out.println("No, the bugs do not share the same data.");
    		return false;
    	}//end of equals method
    and it's designed to merely compare two existing objects. It's not supposed to instantiate anything, which is why I'm confused about the error on line 56 in BugShopApp.java.

    Can you please also give me a link to the tutorials with your signature? I want a much better explanation about static than the one my book gave me.
    Last edited by Sam_JavaTheHut5580; 08-11-2016 at 09:16 PM.

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

    Default Re: How to dynamically work with inheritance

    Your syntax makes no sense.

    Java Code:
    BugShop.equals(bug);//error: Cannot make a static reference to the non-static
    First, you can't use BugShop since it is a class name and not an object reference. And equals is
    an instance method. Hence the static reference error. So within an instance of BugShop you can do the following:

    Java Code:
    this.equals(bug)
    Second, the previous statement does nothing except return a boolean into the bit bucket. So
    you need to capture and use the return value.

    Have you gone thru the tutorials in my signature? You should also write tiny programs (10 lines or so) to test out
    features of the language until you understand how they work.

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

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

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by jim829 View Post
    Have you gone thru the tutorials in my signature? You should also write tiny programs (10 lines or so) to test out
    features of the language until you understand how they work.
    Where and how do I find the tutorials in your signature?

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

    Default Re: How to dynamically work with inheritance

    Click on the first link at the end of my any of my replies.

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

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

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by jim829 View Post
    Click on the first link at the end of my any of my replies.

    Regards,
    Jim
    Right, I've already been to that link, but how do I find YOUR tutorials there?

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

    Default Re: How to dynamically work with inheritance

    I never said they were my tutorials.

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

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

    Default Re: How to dynamically work with inheritance

    I finally found the problem! I had to comment out line #9 in the following code:
    Java Code:
    @Override 
    	public boolean equals(Object object){//overrides the equals method of the java.lang.Object class
    		
    		if(object instanceof BugShop){//If the current BugShop object is an instance from the BugShop
    			//superclass, 
    			BugShop bug2 = (BugShop) object;//then rename that object to bug2, so that we can 
    			//compare it as a separate object to one of the objects defined in the BugShopDB class.			
    			  
    			if(//BugID.equals(bug2.getBugID()) && //if bug and bug2 have same BugID
    				description.equals(bug2.getDescription()) &&
    				price == bug2.getPrice()){				
    				return true;
    			}
    		}
    		return false;
    	}//end of equals method
    The BugID is never the same. That's why the program always outputted that it's not the same bug!

    And thank you jim829, for this quote:
    Quote Originally Posted by jim829 View Post
    First, you can't use BugShop since it is a class name and not an object reference. And equals is
    an instance method. Hence the static reference error.
    It paints a big and important picture.

    In addition, by looking back at chapter 4 in my book, I think I have a better understanding of when to use static methods. Basically, if you want to execute a method, such as a print method, or any method that doesn't need to depend on an object to return a value, that's when you can use static. Is that accurate?
    Last edited by Sam_JavaTheHut5580; 08-12-2016 at 03:27 AM.

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

    Default Re: How to dynamically work with inheritance

    Quote Originally Posted by Sam_JavaTheHut5580 View Post
    In addition, by looking back at chapter 4 in my book, I think I have a better understanding of when to use static methods. Basically, if you want to execute a method, such as a print method, or any method that doesn't need to depend on an object to return a value, that's when you can use static. Is that accurate?
    A static method may return an object. The important thing to remember is that a static method is most often used when the method does not
    rely on any of the object state (e.g. an instance field or call to another instance method). Think about the Math class which are simply static
    methods of math functions. A classic example of instance methods are a setters and getters as you are setting some value that is unique to
    each instance of a given class.

    Note that a field declared static is not an instance field but a class field. Its value is always the same among all instances of a given class.

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

Similar Threads

  1. Replies: 2
    Last Post: 11-25-2012, 02:51 AM
  2. JSP include dynamically
    By raghosh in forum JavaServer Pages (JSP) and JSTL
    Replies: 3
    Last Post: 04-23-2012, 06:24 PM
  3. applet call dll work in Win2000 but not work in WinXP
    By manhcuongtin4 in forum Java Applets
    Replies: 1
    Last Post: 07-14-2011, 01:45 PM
  4. Replies: 2
    Last Post: 12-24-2009, 06:41 PM
  5. subclasses and inheritance - how's it all work?
    By 711groove in forum New To Java
    Replies: 14
    Last Post: 12-18-2009, 09:04 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
  •