Search code examples
javaandroidclassinheritanceandroid-listview

How to use child class in android Java (inheritance)


I am fairly new to coding please help me understand how to use inheritance in android with Java. Let me explain my question with an example :

Like there is a parent class called "Animal" which includes "name" and "age" and has two subclasses "Dog" and "Cat". The "Dog" class has "name", "age", "food" and the "Cat" class has "name", "age", "breed" as their attributes.

From my understanding the best practice is to make:

  1. Animal class with the attribute of "name", "age" + constructor and getter and setter

public class Animal{
    private String name;
    private int age;

    public Animal() {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

  1. Dog class extends of Animal class with an attribute of "food" and put getter and setter
   private String food;
   

    public String getFood() {
        return food;
    }

    public void setFood(String food) {
        this.food = food;
    }
}
  1. Cat class extends of Animal class with an attribute of "breed" and put getter and setter
    private String breed;


    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }
}

  1. MainActivity should be like

public class MainActivity extends AppCompatActivity {

    ArrayList<Animal> mAnimal = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Dog dog = new Dog();
        dog.setName("The Dog");
        dog.setAge(2);
        dog.setFood("Bone");

        Cat cat = new Cat();
        cat.setName("The Cat");
        cat.setAge(1);
        cat.setBreed("Persian");

        mAnimal.add(dog);
        mAnimal.add(cat);

       
    }

}

Now Since there are three classes and each class has a different attribute, How to implement listview to show a list of all animals and their foods or breeds (depends on which one they have) in Mainactivity?

I would really appreciate your answers in advance


Solution

  • Your question Refers to Inheritance but also to polymorphism.

    create a super class and sub classes

    class Animal {
      protected String name;
      protected int age;
    
     public void animalSound() {
        System.out.print("The animal makes a sound");
      }
    }
    
    class Cat extends Animal {
    
      private boolean isLivesAtHome;
    
    //getters & setters
    
    //override function from super class
      public void animalSound() {
        System.out.print("The Cat says meow");
      }
    }
    
    class Dog extends Animal {
    private boolean isWasVaccinatedAgainstRabies;
    
    //getters & setters
    
    //override function from super class
      public void animalSound() {
        System.out.print("The dog says bow wow");
      }
    }
    

    run this on Main function like this:

    class Main {
      public static void main(String[] args) {
        Animal myAnimal = new Animal();  // Create a Animal object - Super Class
        Animal myCat = new Cat();  // Create a Cat object
        Animal myDog = new Dog();  // Create a Dog object
    
            ArrayList<Animal> arr = new ArrayList<>();
            arr.add(myCat);
            arr.add(myDog);
            arr.add(myAnimal);
    
            //simple for loop
            for (int i = 0; i < arr.size(); i++){
    
                //if the object is a Cat instance
                if(arr.get(i) instanceof Cat){
    
                    //change Cat instance variable
                    ((Cat)arr.get(i)).setLivesAtHome(true);
    
                    System.out.println("I'm a Cat");
                }
    
                //print animalSound function
                arr.get(i).animalSound();
            }
      }
    }
    

    This code print's:

    I'm a Cat
    The Cat says meow
    The dog says bow wow
    The animal makes a sound
    

    This example show Polymorphism and inheritance concept using single ArrayList.

    The list is of animals. Of the Super Class type.

    A dog is also an animal, a cat is also an animal (by inheritance) so you can add them to the Animal List.

    If you want to refer a particular object (like the Cat in the example code), you have to use 'instance of' operator for Casting.

    for more info you can read about Inheritance and Polymorphism.