My only issue here is i am not able to invoke line 41
owner.pets[ 3 ].getAction();?

Any ideas why?

Inline Code Example Here

abstract class Pet1 {
    abstract void perform();
}

class Dog extends Pet {
    void perform() { System.out.println("*The dog rolls over*"); }
}
class GoldFish extends Pet{
    void perform() { 
    System.out.println("*GoldFish eats alot*"); }
    public String action = "Blowing bubbles";
    GoldFish(){
    }
    GoldFish( String action ){
    this.action = action;
    }
    public String getAction(){
    return this.action;

    }   
}
class Human {

    String firstName = "Unknown";
    String lastName = "Unknown";
    Pet[] pets = new Pet[ 5 ]; 
    void speak() { System.out.println( "My name is " + firstName + " " + lastName ); }
}
class Example2 {
    public static void main( String[] args ) {
        Human owner = new Human();
        owner.firstName = "Andy";
        owner.lastName = "Cole";
        owner.speak();
        owner.pets[ 0 ] = new Dog();
        owner.pets[ 1 ] = new Fish();
        owner.pets[ 2 ] = new GoldFish();
        owner.pets[ 3 ] = new GoldFish("Hamster");
        owner.pets[ 4 ] = new GoldFish("Iguana");

        owner.pets[ 3 ].getAction(); 

        System.out.println("My pets will perform the following tricks:");
        if ( owner.pets != null ) {
            for ( int i = 0; i < owner.pets.length; i++ ) {
                Pet somePet = owner.pets[i];
                if ( somePet != null ) {
                    somePet.perform();
                }
            }
        }

    }
}

Recommended Answers

All 3 Replies

i am not able to invoke line 41
owner.pets[ 3 ].getAction();?

Do you get compiler errors? If so please post them.
Otherwise explain what the problem is.

Note: the getAction() method returns a String that your code ignores.

Ok below is the error message:

Example2.java:42: error: cannot find symbol
owner.pets[3].getAction();
^
symbol: method getAction()
location: class Pet
1 error

pets is an array of Pets, so pets[ 3 ].getAction() requires the getAction method to be defined for the class Pet, but it's not, it's only defined for GoldFish. I know that you know that pets[3] contains a GoldFish, but that's not something the compiler can figure out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.