Domanda

Is there a use case where we would need an abstract class with no methods defined in it? I bumped into creating such an abstract class just for the sake of generics so that users will pass only subtypes of this class. But I want to know if either is valid or there is a better way to do it.

È stato utile?

Soluzione

Having an abstract class with no methods is legal, yet entirely pointless. You use abstract classes to share implementation. If a class has no methods, it has no implementation to share.

If you need to share some common variables (I assume that your abstract class has at least some fields, otherwise it is entirely empty) you would be better off with composition and an interface, like this:

class CommonData {
    // Some getters and setters for items that you wish to share
}
interface WithCommonData {
    CommonData getCommonData();
}

Your classes can put the common data as a member, and implement the interface WithCommonData, giving you access to the common data, and letting the classes keep their inheritance structure.

If you need to "mark" a user class, doing it with a "marker interface" (i.e. an interface with no methods) is a lot more flexible, because the users retain an ability to build their own chain of inheritance.

Altri suggerimenti

Creating an abstract class just because other classes should be of that type is not neccessary. This can instead be achieved using interfaces. Since a class only can extend one class but implement any number of interfaces, using an interface as an instance validator will not limit a solution with respect to inheritance.

Example:

public interface Vehicle {
    // No methods, we just want several classes to be identified as of type Vehicle
}


public class Car implements Vehicle {
    // is a vehicle
}

public class Motorcycle implements Vehicle {
    // is a vehicle
}

public class Banana {
    // is not a vehicle
}

public class Main {
    public static void main(String[] args) {

        Object o = new Car();
        if(o instanceof Vehicle) {
            // Ok
        }

        Object p = new Banana();
        if(p instanceof Vehicle) {
            // Will never get here
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top