Search code examples
javaoopinterfaceabstraction

Abstract class and mandatory methods of childs?


I have this abstract base class and each of it's childs should have a specific mandatory function but slightly different. Is this possible using the abstract class or should I be using an interface for this?

I will be using the structure like this

public abstract class Animal
{
    //Mandatory method
    Public void sound()
    {

    }
}

public class Cat extends Animal
{
    public void sound()
    {
        System.out.println("Miauw");
    }
}

public class Dog extends Animal
{
    public void sound()
    {
        System.out.println("Woof");
    }
}

//I will put all these child objects in a List<Animal> and need to call these methods.

for (Animal a : animalList)
{
    a.sound();
}

How would one go about this structure? I have to add that I am using an abstract class because there are plenty of identical methods that need to be shared among the child classes. Just some of the methods need to be different from each other but mandatory and accessible from the base class.


Solution

  • You are looking for:

    public abstract class Animal
    {
        //Mandatory method
        abstract public void sound();
    }
    

    But also look at other users advices:

    • use lowercase for method names
    • the keyword publicalways goes in lowercase
    • use interfaces if your Animal class hasn't common code for all children classes