Results 1 to 11 of 11
  1. #1
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default inhertiance problem what am i doing wrong?

    hey guys!

    basically my task it to create 2 types on Animal, this case Cat and Dog and add them to a kennel. the problem i am having is, adding them and creating them the way the specification tells me to.

    my brief is, Create 2 types of animal using inheritance, add them to your kennel, allow for user creation using an interface menu.

    i can do it easy without inheritance but when i add the inheritance i get null pointers in my program.

    i tried putting the creations in a method and call that method but i still get a null pointer in my Kennel class with the addNewAnimal(); method

    ANIMAL - CAT AND DOG CLASS

    Java Code:
    import java.util.*;
    import java.io.*;
    /**
     * 
     * To model a Kennel - a collection of dogs
     *
     */
    public class Animal extends Kennel{
        //holds dog class and allows dog creation
        protected String name;
        protected String owner;
        protected String type;
    
        /**
         * New default constructor
         * 
         */
        public Animal() { 
            name="unkown";
            owner="unknown";
            type="unknown";
        }
    
        public Animal(String n, String o, String t) {
            n=name;
            o=owner;
            t=type;
    
        }
    
        /**
         * This method sets the value for the name attribute. 
         * The purpose of the attribute is: 
         * The name of the Kennel e.g. "DogsRUs"
         * 
         *
         * 
         * @param theName
         */
        public void setName(String theName)  
        {
            name = theName;
        }
    
        /**
         * This method gets the value for the name attribute. 
         * The purpose of the attribute is: 
         * The name of the Kennel e.g. "DogsRUs"
         * 
         *
         * 
         * @return String
         */
        public String getName()  
        {
            return name;
        }
    
        /**
         * This method returns the number of dogs in a kennel
         * 
         *
         * 
         * @return int
         */
        public void addAnimal() {
            String animal;
            animal=scan.nextLine();
            System.out.println("do you want to add a cat or a dog?");
            if (animal.equals("cat") || (animal.equals("CAT"))){
                this.addCat(c);
                return;
            }
            else if(animal.equals("dog") || (animal.equals("DOG"))){
    
                this.addDog(d);
                return;
            }
            else {
                System.out.println("Inavlid entry, eneter 'cat' or 'dog'");
                return;
            }
        }
    
        /**
         * Enables a user to add a Dog to the Kennel
         * This is ran via the demo class as Kennel holds the array
         * It is called when the user inputs "1" as a repsonce.
         * @param Dog d
         */
        public void addCat(Cat c) {  
            c=new Cat();
    
            System.out.println("enter name of Cat:");
            String name=scan.nextLine();
            System.out.print("enter name of Cat's Owner: \n");
            String owner=scan.nextLine();
            type="cat";
            System.out.print("does Cat share a run? TRUE/FALSE \n");
            boolean run=scan.nextBoolean();
            //finished constructing dog(x, x, x);
            c=new Cat(name, owner, type, run);
            //animals.add(c);
    
        }
    
        public void addDog(Dog d) {  
            d=new Dog();
            System.out.println("enter name of Dog:");
            String name=scan.nextLine();
            System.out.print("enter name of Dog's Owner: \n");
            String owner=scan.nextLine();
            type="dog";
            System.out.print("does the Dog need walks? TRUE/FALSE \n");
            boolean walks=scan.nextBoolean();
            //finished constructing dog(x, x, x);
            d=new Dog(name, owner, type, walks);
            animals.add(d);
        }
    }
    Java Code:
    public class Dog extends Animal{
        private boolean needswalk;
    
        public Dog() {
            super();
        }
    
        public Dog(String n, String o, String t, boolean walks) {
            super(n,o,t);
            needswalk=walks;
    
        }
    
        public void setWals(boolean walks){
    
            needswalk=walks;
        }
    
        public boolean getWalks() {
    
            return needswalk;
    
        }
    
        public void setType(String startType) {
            type=startType;
        }
    
        public String getType() {
    
            return type;
        }
    
        public String toString(){
            if(this.getWalks()==true){
                return " This is a Cat and is called " +name+ " and belongs to " 
                +owner+ " and needs walks ";
            }
            else {
                return  " This is a Cat and is called " +name+ " and belongs to " 
                +owner+ " and is happy with the run provided ";
            }
        }	
    }
    Java Code:
    public class Cat extends Animal{
        private boolean canshare;
    
        public Cat() {
            super();
        }
    
        public Cat(String n, String o, String t, boolean share) {
            super(n,o,t);
            canshare=share;
    
        }
    
        public void setShare(boolean share) {
    
            canshare=share;
        }
    
        public boolean getShare() {
    
            return canshare;
        }
    
        public void setType(String startType) {
    
            type=startType;
        }
    
        public String getType() {
    
            return type;
        }
        
        public String toString(){
            if(this.getShare()==true){
                return " This is a Cat and is called " +name+ " and belongs to " 
                +owner+ " and can share a run ";
            }
            else {
                return  " This is a Cat and is called " +name+ " and belongs to " 
                +owner+ " and can't share a run ";
            }
        }	
    }
    KENNEL CLASS

    Java Code:
    import java.util.*;
    import java.io.*;
    /**
     * 
     * To model a Kennel - a collection of dogs
     *
     */
    public class Kennel {
        private Animal an;
        protected Dog d;
        protected Cat c;
        private String kennelname;
        protected Scanner scan; // for user input method
        protected List<Kennel> animals;  
        private int nextFreeLocation;
        private int capacity;  //max amout of dogs allowed in ArraList<Dog>;
    
        /**
         * New default constructor
         * 
         */
        public Kennel(){
        }
    
        public Kennel(int maxNoAnimals) { 
            nextFreeLocation = 0;   // no Dogs in collection at start
            capacity=maxNoAnimals;
            scan=new Scanner(System.in);
            animals = new ArrayList<Kennel>(capacity);  //set up default 10 dogs
        }
    
        /**
         * This method sets the value for the name attribute. 
         * The purpose of the attribute is: 
         * The name of the Kennel e.g. "DogsRUs"
         * 
         *
         * 
         * @param theName
         */
        public void setName(String theName)  
        {
            kennelname = theName;
        }
    
        /**
         * This method gets the value for the name attribute. 
         * The purpose of the attribute is: 
         * The name of the Kennel e.g. "DogsRUs"
         * 
         *
         * 
         * @return String
         */
        public String getName()  
        {
            return kennelname;
        }
    
        /**
         * This method returns the number of dogs in a kennel
         * 
         *
         * 
         * @return int
         */
        public int getNumOfAnimals()   
        {  
            return nextFreeLocation;
        }
    
        /**
         * Enables a user to add a Dog to the Kennel
         * This is ran via the demo class as Kennel holds the array
         * It is called when the user inputs "1" as a repsonce.
         * @param Dog d
         */
        public void addNewAnimal() {
    
            an.addAnimal();
    
        }
    
        /**
         * Enables a user to delete a Dog from the Kennel.
         * Searches the ArrayList<Dog> dogs: for "name"
         * if it find this it will remove the dog, 
         * return jumps it out the method so afetr deletion method is stopped
         * @param name
         */
        public void removeAnimal(String name) {
            //search for dog and remove fromm array list
            String x;
            System.out.println("remove cat or dog?");
            x=scan.nextLine();
            if(x.equals("cat") || (x.equals("CAT"))) {
                for (Kennel a:animals) {
                    if (name.equals(a.getName()))  {
                        animals.remove(a);
                        return;
                    }
                }
            }
            else if(x.equals("dog") || (x.equals("DOG"))){
                for (Kennel a:animals) {
                    if (name.equals(a.getName()))  {
                        animals.remove(a);
                        return;
                    }
                }
    
                System.out.println("not on list");
            }
    
            
        }
    
        public void searchForAnimalAndPrint(String name){
    
            //search for dog and print its tooString
    
            for (Kennel a:animals) {
                if (name.equals(a.getName()))  {
                    System.out.println(a.toString());
    
                }
            }
            System.out.println("not on list");
        }
    
        
        public void printAll(){
            for (Kennel a:animals) 
                System.out.println(a.toString());
        }
    }
    MENU - BASICALLY USE UI

    Java Code:
    public class KennelDemo
    {
        private Dog d;
        private Cat c;
        private String filename;    //holds the name of the file
        private Kennel kennel;      //holds the kennel
        private Scanner scan; 
    
        public KennelDemo()
        {
            System.out.println("**constructor for KennelDemo");
            scan=new Scanner(System.in);
            System.out.print("Please enter the file name of kennel information: ");
            filename=scan.next();
            System.out.print("enter max number of dogs: ");
            int max=scan.nextInt();scan.nextLine();
            kennel=new Kennel(max);
        }
    
        /**
         * initialise() method runs from the main and reads from a file - calls load(filename) in Kennel
         */
        public void initialise()
        {
            /*
            System.out.println("**method initialise reads from a file");
            System.out.println("Using file "+filename);
            //calls the load file method in Kennel, with specified file name.
            kennel.load("dogs.txt"); 
    
            }
             */
    
            /**
             * runMenu() method runs from the main and allows entry of data etc
             */
        }
    
        public void runMenu()
        {
            scan=new Scanner(System.in);
            String response; // for user with user choice in the menus
            String n; // thisis for use in search methods to pass params
    
            do {
                printMenu();
                response=scan.nextLine();
    
                if (response.equals("1")) {
    
                    kennel.addNewAnimal(); // calls the add dog method
    
                }
                else if (response.equals("2")){
    
                    
                }
                else if (response.equals("3")) {
                    kennel.printAll();
                } 
                else if(response.equals("4")) {
    
                }
                else if(response.equals("5")) {
                    // start user input for name search
                    System.out.println("Enter name to Search for");
                    n=scan.nextLine();
                    // use input to run kennel method
                    kennel.searchForAnimalAndPrint(n); // this is the string 'n' from earlier
    
                }
                else if(response.equals("6")) {
                    //start user input
                    System.out.println("Enter the name of the dog you wish to remove");
                    n=scan.nextLine();
                    // use input to run method
                    kennel.removeAnimal(n); // string 'n' from earlier
    
                }
    
            }while (!( (response.equals("Q"))|| (response.equals("q"))));
        }
    
        /**
         * printAll() method runs from the main and prints status
         */
    
        public void printAll()
        {
            System.out.println("**method printAll prints");
            System.out.println(kennel);
        }
    
        /**
         * save() method runs from the main and writes back to file - calls save(filename) in Kennel
         */
        public void save()
        {
            System.out.println("**method save writes data back to a file");
            // put your code here
    
        }
    
        private void printMenu() {
            System.out.println("1 - Add a new Cat or Dog?");          
            System.out.println("2 - does nothing atm");
            System.out.println("3 - Print list of animals");
            
            System.out.println("5 - Search for a Animal and Print");
            System.out.println("6 - Search for a Animal and remove it from the kennel");
            System.out.println("Q - quit");
    
        }
    
    }

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

    Default Re: inhertiance problem what am i doing wrong?

    Right away I see a big problem with your code: you shouldn't have Animal extend Kennel. If you think on this it should be clear since an Animal is in no way shape or form a type of Kennel, and in fact they are two completely different concepts. I would expect Animal to inherit from nothing (other than the default parent class, Object, which all classes ultimately inherit from), and possibly even be an abstract class.

  3. #3
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: inhertiance problem what am i doing wrong?

    i thought that myself, i tried it wihtout the extends on it as well but i couldnt get it to work because the array list was in a completely different class, so i just throw the extends in to try and fluke a working program. ill go and have a play then come back if i screw it up! cheers.

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

    Default Re: inhertiance problem what am i doing wrong?

    Animal shouldn't have an ArrayList inside of it. All it should have are the basic behaviors shared by all animals. It shouldn't have an addAnimal() or addDog() or addCat() method, and in fact should have no knowledge about its possible subclasses whatsoever.

  5. #5
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: inhertiance problem what am i doing wrong?

    had a play around, a bit but now i have this issue which i couldn't figure out before how do i add my animal to the array list in kennel?

    these are my methods to make a Cat (in cat class which inherits animal and same for dog)

    Java Code:
     public void addDog(Dog d) {  
            d=new Dog();
            System.out.println("enter name of Dog:");
            name=scan.nextLine();
            System.out.print("enter name of Dog's Owner: \n");
            owner=scan.nextLine();
            type="dog";
            System.out.print("does the Dog need walks? TRUE/FALSE \n");
            boolean walks=scan.nextBoolean();
            //finished constructing dog(x, x, x);
            d=new Dog(name, owner, type, walks);
            animals.add(d);
        }
    Java Code:
    public void addCat(Cat c) {  
            c=new Cat();
    
            System.out.println("enter name of Cat:");
            name=scan.nextLine();
            System.out.print("enter name of Cat's Owner: \n");
            owner=scan.nextLine();
            type="cat";
            System.out.print("does Cat share a run? TRUE/FALSE \n");
            boolean run=scan.nextBoolean();
            //finished constructing dog(x, x, x);
            c=new Cat(name, owner, type, run);
            animals.add(c);
    
        }
    would i create a method in kennel say like

    Java Code:
    public class Kennel {
    
    private Cat c;
    private Dog d;
    protected ArrayList<Kennel> animals;
    
    public void addAnimal() {
    String animal;
    animal=scan.nextLine();
    
    if(animal.equals("dog")) {
    
    c.addCat(Cat c);
    
    }
    else if(animal.equals9"dog")) {
    d.addDog(Dog d);
    }
    else {
    System.out.println("invalid entry");
    }
    }
    }
    im stumped here

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: inhertiance problem what am i doing wrong?

    Think on this for a moment. What will the ArrayList be holding in it? Currently you have it written as an ArrayList<Kennel> or a list that will hold a bunch of Kennel objects. Does this make sense? Think on this -- what should this ArrayList be holding?

    Also, I would give the Kennel class an addAnimal(Animal animal) method and would not give it an addCat, addDog or anything similar. Also, the Kennel should not have a Cat c or Dog d variable as they serve no purpose.

  7. #7
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: inhertiance problem what am i doing wrong?

    right ok. sorry about this, first time using inheritance :L ill try cook something up with that info. so the <Kennel> is not the class it's in, its what the elements are in the array
    so i should use <Animal>

  8. #8
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: inhertiance problem what am i doing wrong?

    YOU LEGEND!
    basically taught my about inheritance is there like "rep" i can give you?

    final method:

    Java Code:
    public void addAnimal(Animal a) {
    
            a=new Animal();
            System.out.println("enter name of Animal:");
            String name=scan.nextLine();
            System.out.print("enter name of Dog's Owner: \n");
            String owner=scan.nextLine();
            System.out.print("enter type of Animal:\n");
            String type=scan.nextLine();
            if(type.equals("cat")){
                System.out.print("does your cat share a run?");
                boolean share=scan.nextBoolean();
                a=new Cat(name, owner, type, share);
                animals.add(a);
            }
            else if(type.equals("dog")){
                System.out.print("does your dog require walks?");
                boolean walks=scan.nextBoolean();
                a=new Cat(name, owner, type, walks);
                animals.add(a);
            }
            else {
                System.out.print("please enter car ot dog");
            }

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: inhertiance problem what am i doing wrong?

    Quote Originally Posted by monkeyjr97 View Post
    YOU LEGEND!
    basically taught my about inheritance is there like "rep" i can give you?

    final method:

    Java Code:
    public void addAnimal(Animal a) {
    
            a=new Animal();
            System.out.println("enter name of Animal:");
            String name=scan.nextLine();
            System.out.print("enter name of Dog's Owner: \n");
            String owner=scan.nextLine();
            System.out.print("enter type of Animal:\n");
            String type=scan.nextLine();
            if(type.equals("cat")){
                System.out.print("does your cat share a run?");
                boolean share=scan.nextBoolean();
                a=new Cat(name, owner, type, share);
                animals.add(a);
            }
            else if(type.equals("dog")){
                System.out.print("does your dog require walks?");
                boolean walks=scan.nextBoolean();
                a=new Cat(name, owner, type, walks);
                animals.add(a);
            }
            else {
                System.out.print("please enter car ot dog");
            }
    I would change the above. For one, the method is written to accept an Animal into the Kennel via its parameter. So you must assume that a living Animal (OK a non-null Animal object) is being passed into the method through the parameter. So there is no need for this method to create a new Animal, and in fact it shouldn't since Kennel's aren't really in the business of creating new animals.

    Instead some driver class will create the Kennel and then some Dogs and Cats, and will place these Animals into the Kennel by calling the Kennel's addAnimal method. This method will be much shorter than your currently written method, and all it will do is to add the Animal to the Kennel's ArrayList, that's it.

  10. #10
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    2

    Default Re: inhertiance problem what am i doing wrong?

    cheers mate, im back in uni tomorrow ill see them about it, hit a sticky situation, no matter what i enter as input for type when i print the arraylist type is always cat, and which ever boolean value was entered last, is what they all change to :/ logic errors are horrid!

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    18

    Default Re: inhertiance problem what am i doing wrong?

    That sounds like you are sharing a single instance of an object and simply changing the values.
    eg:
    Java Code:
    List<SomeClass> obj = new ArrayList<SomeClass>();
    SomeClass temp = new SomeClass();
    // Populate the list
    for (int i = 0; i < 10; i++) {
        temp.setId(i);
        obj.add(temp);
    }
    // Print my array of objects
    for (SomeClass sc : obj) {
        System.out.println(temp.getId());
    }
    All I have done there is stick the same object into the List 10 times.
    There are now 10 references to that object...and the id will be 9.
    So the print out will be a load of 9's.
    Please do not ask for code as refusal often offends.

Similar Threads

  1. Replies: 4
    Last Post: 06-11-2013, 01:37 AM
  2. I can't find anything wrong with this but somehow it's wrong.
    By Biscuit Tickler in forum New To Java
    Replies: 2
    Last Post: 09-12-2012, 09:28 PM
  3. What went wrong. Methods problem.
    By ocean in forum New To Java
    Replies: 5
    Last Post: 11-02-2009, 06:28 PM
  4. What am I doing wrong in this basic problem
    By Blaedel in forum New To Java
    Replies: 10
    Last Post: 10-11-2009, 07:45 PM
  5. Wats the problem here ? anythig wrong with IDE
    By Shyam Singh in forum New To Java
    Replies: 6
    Last Post: 07-17-2008, 04:17 PM

Posting Permissions

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