0

I'm a bit confused with inheritance/interfaces in Java/Android and am not sure if I'm on the right track. Basically I'm using Parcelable in Android and am getting errors because methods are undefined.

I've got an Animal superclass, and a few subclasses (Dog, cat etc). On the first activity you select an animal then it parcels it up and passes it to the second activity:

/* Second activity */
Animal myAnimal;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_current_status);

    Intent intent = getIntent();
    myAnimal = intent.getParcelableExtra("animal"); // Gets the animal subclass (dog, cat etc) from the previous activity
    myAnimal.updateImage(myAnimal.getCurrentState());
}

The problem is 'updateImage' only exists in the subclass, therefore it won't compile here. I don't want this method to be in the superclass, because the output varies depending on the type of animal (e.g. picture of a dog).

I also don't know which type of animal it is going to be, so I can't define the variable as anything other than 'Animal' at the top. I did try defining the variable as an interface which all subclasses implement, which did make 'updateImage' available, but then it wasn't find methods in the superclass as that does not implement this particular interface.

Hopefully that makes sense, any advice on how I should approach this will be much appreciated.

Loop77
  • 98
  • 6

2 Answers2

0

I don't want this method to be in the superclass, because the output varies depending on the type of animal

This is fine. Define it in the superclass as an abstract method and then each subclass is required to implement it.

public abstract class Animal {

    public void abstract updateImage();
}

public class Dog extends Animal {

    public void updateImage() {
        // Do dog-specific stuff here
    }
}

public class Cat extends Animal {

    public void updateImage() {
        // Do cat-specific stuff here
    }
}

Note, I have not added the state parameter to the updateImage method as you have not provided information on the type returned from getCurrentState.

This link will hopeful help: http://www.java-made-easy.com/java-inheritance.html

JamesB
  • 7,774
  • 2
  • 22
  • 21
0

Declare the Animal class abstract with updateImage method abstract and implement it in the subclasses. You can find something helpful here

Community
  • 1
  • 1