13 Replies - 436 Views - Last Post: 11 November 2012 - 08:58 PM Rate Topic: -----

#1 toad87  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 188
  • Joined: 21-May 12

Classes of Abstract classes problem

Posted 11 November 2012 - 01:49 PM

My situation:

I have a hiearchy with 3 classes. Animal<----Dog<----Husky

I have a seperate classs that calls a method that is contained ONLY in Husky Class. I make the Animal abstract and add that method in as abstract. But now it wants me to make Dog abstract with that abstract method in there too. Not only that but if I had a Cat subclass, that must also be abstract!

I don't want my Dog or Cat classes to be abstract. I want to be able to create different Dog's and Cat's at the spur of the moment!

What should I do in this case?

Is This A Good Question/Topic? 0
  • +

Replies To: Classes of Abstract classes problem

#2 GregBrannon  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2204
  • View blog
  • Posts: 5,236
  • Joined: 10-September 10

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 02:01 PM

Quote

I have a seperate classs that calls a method that is contained ONLY in Husky Class. I make the Animal abstract and add that method in as abstract.

Why did you add the method that ONLY exists in the Husky class as an abstract method to the Animal class?

None of your subclasses, Dog, Cat, Husky, or the separate unnamed class have to be abstract unless they have abstract methods, so don't give them abstract classes.
Was This Post Helpful? 0
  • +
  • -

#3 toad87  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 188
  • Joined: 21-May 12

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 02:08 PM

Oh and if you're wondering, "Why would you have a specific Class for Husky?".

Well what if I wanted to make and put 100 Husky's and 50 GoldenRetrievers, in one room. Instead of initializing each Dog class 100 and 50 times with the same info, I can just create 100 and 50 instances of Husky and GoldenRetrievers.

Not only that but Husky and GoldenRetriever can have different fields and methods from eachother.

Is my thinking right here?

View PostGregBrannon, on 11 November 2012 - 02:01 PM, said:

Quote

I have a seperate classs that calls a method that is contained ONLY in Husky Class. I make the Animal abstract and add that method in as abstract.

Why did you add the method that ONLY exists in the Husky class as an abstract method to the Animal class?


Well say I have a class called AnimalHotel that holds an arraylist of animals. If that class needs to call a method that is only in Husky it will give me an error saying, "That method does not exist in Animal". So that's why I made that class abstract.

This post has been edited by toad87: 11 November 2012 - 02:10 PM

Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,885
  • Joined: 06-March 08

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 03:45 PM

View Posttoad87, on 11 November 2012 - 04:49 PM, said:

I have a seperate classs that calls a method that is contained ONLY in Husky Class. I make the Animal abstract and add that method in as abstract.

This is not the way it works

If the class is only to be used in the Husky class it shouldn't be declared as abstract in the Animal class.
The Animal class should only includes the method used by ALL its descendants.
Was This Post Helpful? 0
  • +
  • -

#5 toad87  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 188
  • Joined: 21-May 12

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 04:54 PM

I guess you're saying I need to rethink my hiearchy structure?
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,885
  • Joined: 06-March 08

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 04:58 PM

Not the hierarchy structure it is perfect.
But neither Animal or Dod have to know what is proper to Husky.
Simply declare only in Husky what is proper to Husky.

That is what will differentiate Husky to Labrador to ShiTsu to Poddle: the diferrent methods they own.

This post has been edited by pbl: 11 November 2012 - 04:59 PM

Was This Post Helpful? 0
  • +
  • -

#7 toad87  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 188
  • Joined: 21-May 12

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 05:13 PM

But how can I call a method from Husky from another Class that contains an arraylist of Animal then? It won't compile. It will say that method does not exist in Animal.
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,885
  • Joined: 06-March 08

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 05:17 PM

Animal a = arrayList.get(i);
if(a instanceof Husky) {
   Husky h = (Husky) a;
   h.methodProperToHusky();
}



of if you don't mind (())
Animal a = arrayList.get(i);
if(a instanceof Husky) {
   ((Husky) a).methodProperToHusky();
}


Was This Post Helpful? 0
  • +
  • -

#9 toad87  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 188
  • Joined: 21-May 12

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 07:11 PM

PBL that makes total sense to me in the scenario I pointed out to you. But let me show you what I'm actually working on.

Item Class:

//checked
/**
 * Item - An object in the game that the player can see and may or may not pick up, eat, or wear.
 * 
 * @author Brandon Tran
 * @version 10-10-2012
 */
public abstract class Item
{
    // instance variables - replace the example below with your own
    private String itemName;
    private String itemDesc;
    private int itemWeight;
    private boolean pickUpAble;
    private boolean eatAble;
    
    public Item()
    {
    }
    /**
     * Constructor for objects of class Item
     * @param name The name of the item.
     * @param description A brief description of the item.
     * @param weight The weight of the item in integers.
     * @param pickUpAble True if item can be picked up; false otherwise.
     */
    public Item(String name, String description, int weight, boolean pickUpAble, boolean eatAble)
    {
        itemName = name;
        itemDesc = description;
        itemWeight = weight;
        this.pickUpAble = pickUpAble;
        this.eatAble = eatAble;
    }

    /**
     * Return the name of the item.
     * @return The name of the item.
     */
    public String getItemName()
    {
        return itemName;
    }

    /**
     * Return a description of the item.
     * @return The description of the item.
     */
    public String getDesc()
    {
        return itemDesc;   
    }

    /**
     * Return the weight of the item.
     * @return The weight of the item.
     */
    public int getWeight()
    {
        return itemWeight;
    }
    
    /**
     * Sees if item is pickupable or not.
     * @return True if item can be picked up; false otherwise.
     */
    public boolean isPickUpAble()
    {
        return pickUpAble;
    }
    
     public boolean isEatAble()
    {
        return eatAble;
    }
    
    /**
     * Change the item's name.
     * @param name The items new name.
     */
    public void setName(String name)
    {
        itemName = name;
    }

    /**
     * Change the item's description
     * @param description The items new description.
     * 
     */
    public void setDesc(String description)
    {
        itemDesc = description;
    }

    /**
     * Change the item's description
     * @param weight The items new weight.
     * 
     */
    public void setWeight(int weight)
    {
        itemWeight = weight;
    }

    /**
     * Returns all the info for the item.
     */
    public String toString()
    {
        StringBuilder builder = new StringBuilder();
        builder.append(itemName);
        builder.append('\n');
        builder.append(itemDesc);
        builder.append('\n');
        builder.append("Weight: " + itemWeight);
        builder.append('\n');
        
        if(pickUpAble = true){
            builder.append("Pickupable: Yes");
        }else{
            builder.append("Pickupable: No");
        }
        
        
        return builder.toString();
    }
    
    public void displayItem()
    {
        System.out.println(toString());
    }
    
    
    
}


SaleItem Class:

//checked
import java.text.DecimalFormat;
/**
 * SaleItem - Extends Item - Adds a salePrice field to the item.  SaleItems are always pickUpAble (true).
 * 
 * @author Brandon
 * @version 30-10-2012
 */
public class SaleItem extends Item
{
   
    private double salePrice;

    /**
     * Constructor for objects of class SaleItem
     * @param name the name of the item
     * @param description short description of item
     * @param weight the weight of item in int
     * @param salePrice the price of the item
     */
    public SaleItem(String name, String description, int weight, double salePrice, boolean eatAble)
    {
        super(name, description, weight, true, eatAble);
        this.salePrice = salePrice;
        
    }

    /**
     * Get the salePrice
     * @return the sale price of the item.
     */
    public double getSalePrice()
    {
        return salePrice;
    }

    /**
     * Change the sale price of the item.
     * @param salePrice the new sale price.
     */
    private void setSalePrice(int salePrice)
    {
        this.salePrice = salePrice;

    }

    /**
     * Returns a string of the name and cost of the item.
     * @return a string of the name and cost of the item.
     */
    public String toString()
    {
        DecimalFormat df = new DecimalFormat("0.00");
        StringBuilder builder = new StringBuilder();
        builder.append(super.toString());
        builder.append('\n');
        builder.append("Sale Price: " + df.format(salePrice));
        
        return builder.toString();
    }
    
    

}



UseAbleItem Class:

//checked
/**
 * UseAbleItem - Extends SaleItem. This item can be eatable or equipable.
 * 
 * @author Brandon
 */
public class UseAbleItem extends SaleItem
{
    // instance variables - replace the example below with your own
  

    /**
     * Constructor for objects of class UseAbleItem
     * @param name the name of the item
     * @param description short description of item
     * @param weight the weight of item in int
     * @param salePrice the price of the item
     * @param eatAble True if item is eatable; false otherwise
     */
    public UseAbleItem(String name, String description, int weight, double salePrice, boolean eatAble)
    {
        super(name, description, weight, salePrice, eatAble);
        
    }
    
    
    
    
    //blah
     

   
}



Food Class:

//needs to buff and restore player.
/**
 * Food - extends UseAbleItems.  Food items are eatAble and restore/temporarily enhances the players attributes.
 * 
 * @author Brandon
 */

public class Food extends UseAbleItem
{
    private int restoreHealth;
    private int tempDefBonus;
    private int tempHitBonus;
    private int durationTurns;
    
    /**
     * Constructor for objects of class 
     * @param name the name of the item
     * @param description short description of item
     * @param weight the weight of item in int
     * @param salePrice the price of the item
     * @param restoreHealth adds points to health bar of character
     * @param tempDefBonus temporarily grants more def for the user
     * @param tempHitBonus temporarily grants the user more hitting power
     * @param durationTurns the duration the item lasts. Calculated in turns.
     */
    public Food(String name, String description, int weight, double salePrice, int restoreHealth, int tempDefBonus, int tempHitBonus, int durationTurns)
    {
        super(name, description, weight , salePrice, true);
        this.restoreHealth = restoreHealth;
        this.tempDefBonus = tempDefBonus;
        this.tempHitBonus = tempHitBonus;
        this.durationTurns = durationTurns;
    }
    
    public int getRestoreHealth()
    {
        return restoreHealth;
    }
    
    public int getTempDefBonus()
    {
        return tempDefBonus;
    }
    
    public int getTempHitBonus()
    {
        return tempHitBonus;
    }
    
    public int getDurationTurns()
    {
        return durationTurns;
    }
    
}



HealthPotion Class:

//checked
/**
 * HealthPotion - extends Food.  HealthPotion restores the players health by 25 points after being consumed.
 * 
 * @author Brandon
 */
public class HealthPotion extends Food
{

    /**
     * Constructor for objects of class HealthPotion
     */
    public HealthPotion()
    {
        super("Health Potion", "Drink to restore your health", 2, 5, 25, 0, 0, 0);
    }
}





OK so I also have a Room Class that holds an ArrayList of Item.

I add HealthPotion to that arraylist.

My Player Class accesses that room to eat() that HealthPotion. M

My eat() method checks the boolean isEatAble to see if I can eat it. Only Food and it's subclasses have true for this variable.

I can't use the instanceof operator because HealthPotion is a subclass of Food. It's not really Food. I could just do instanceof HealthPotion, but what if I had other Food subclasses like chicken or lamb?

This post has been edited by toad87: 11 November 2012 - 07:12 PM

Was This Post Helpful? 0
  • +
  • -

#10 toad87  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 188
  • Joined: 21-May 12

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 07:26 PM

Omg I think I got it. I will make SaleItem, UseAbleItem, and NonUseAbleItem, and NonSaleItem abstract!

Let me show you a picture of my hierarchy and tell me what you think. I think this will work because I will never make an instance of any of the above classes.

It's in BlueJ so it's easy to see.

https://www.dropbox....03c8jj/Item.jpg
Was This Post Helpful? 0
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,885
  • Joined: 06-March 08

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 07:29 PM

Those subclassing exercises are purely academic, never in the real life you will have a class/subclass hierarchy that goes more than 3 levels
Your Husky class in your first posts were the extreme limit. What Husky do have a particular that requires them to have there proper class as Basset and Poddle ?
May be the class Dog can have simple enum Breed

Anyhow in your last example we have

Item -> SaleItem -> UseAbleItem -> Food -> HealthPotion

OK this is an academic exercide
If you do not have other classes that extend Item no need to have SaleItem to extend Item
If you do not have at least 2 classes that extend SaleItem no need to extend it
If you do not have at least 2 classes that extend UseAbleItem no need to extend it
...
in the real life, when you will have a server that will create 35,000 HelathPotion a second do you seriously think you can have the HealthPotion constructor to call The Food constructor to call the UseABleItem constructor to call the SaleItem constructor to call the Item constructor that will finally call the Object constructor ???

Ok, so in real life only a max of 3 levels. Agreed ?
Now, back to your original problem:
I can't use the instanceof operator because HealthPotion is a subclass of Food. It's not really Food.


Yes if it is a subclass of Food it has to be a food. You like it or not.

This post has been edited by pbl: 11 November 2012 - 08:25 PM
Reason for edit:: Fixed bold tag

Was This Post Helpful? 0
  • +
  • -

#12 toad87  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 188
  • Joined: 21-May 12

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 08:22 PM

That's interesting. Only 3 levels in real life? Sounds a little limiting. Makes sense though. I guess it would be straining for a server to go through all that work.

Anyways, I figured out my problem without changing any of my Item classes. I did not realize that instanceof will search for a class AND all of it's subclasses.

Thank you so much PBL.

Take a look at my new eat() method:

public void eat(Command command)
    {
        if(!command.hasSecondWord()) {
            // if there is no second word, we don't know where to go...
            System.out.println();
            System.out.println("Which item (number) would you like to consume?");

        }

        String second = command.getSecondWord();
        int itemNum = Integer.parseInt(second);
        if(super.getItem(itemNum) != null){
            
            if(super.getItem(itemNum) instanceof Food){
                Food item = (Food)super.getItem(itemNum);
                
                System.out.println(super.getHealthPoints());
                System.out.println(item.getRestoreHealth());
                
                super.setHealthPoints(super.getHealthPoints() + item.getRestoreHealth());
                super.setDefensePoints(super.getDefensePoints() + item.getTempDefBonus());
                super.setHitPoints(super.getHitPoints() + item.getTempHitBonus());

                super.deleteItem(itemNum);
                System.out.println();
                System.out.println("That was delicious.");

            }else{
                System.out.println("You may only eat food.");

            }
        }else{

            System.out.println("That item is not in your list.");

        }
    }




My problem now though...The method is not changing my stats. I eat the item, but my health points remain the same.

Thanks for the lesson in abstraction though. It helped me out ALOT!
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,885
  • Joined: 06-March 08

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 08:30 PM

View Posttoad87, on 11 November 2012 - 11:22 PM, said:

That's interesting. Only 3 levels in real life? Sounds a little limiting.

Limiting in whic sense ? I can garanty you than out of the academic exercise you will not really need it.

Quote

I did not realize that instanceof will search for a class AND all of it's subclasses.

Than you missed the concept. A Husky is a Dog which is an Animal

so Husky instance of Husky or instanceof Dog or instanceof Animal is true
Was This Post Helpful? 0
  • +
  • -

#14 toad87  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 188
  • Joined: 21-May 12

Re: Classes of Abstract classes problem

Posted 11 November 2012 - 08:58 PM

I wish I can eat your brain and gain your knowledge :).

Thanks for everything PBL. I finally got everything to work.

My eat method wasn't adding because of a typo in my set method's parameter.

I redid my classes and got rid of unnecessary ones too. Things just got a little bit simpler :).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1