A subtype is established when a class is linked by means of extending or implementing. Subtypes are also used for generics.
How can I differentiate subtyping from subclasses?
Subclasses allow one to reuse the code inside classes - both instance variable declarations and method definitions. Thus they are useful in supporting code reuse inside a class. Subtyping on the other hand is useful in supporting reuse externally, giving rise to a form of polymorphism.
Subclasses are classes that can be derived from a parent class by adding some functionality, such as new object variables or new methods. In terms of automaton theory, a subclass adds new states and new rows to the state transition table.
The difference between the Superclass and Subclass is that Superclass is the existing class from which new classes are derived while Subclass is the new class that inherits the properties and methods of the Superclass.
Subtyping is a key feature of object-oriented programming languages such as Java. In Java, Sis a subtype of T if S extends or implements T. Subtyping is transitive, meaning that if R is a subtype of S, then R is also a subtype of T (T is the super type of both Sand R).
In Java, subclassing is a kind of subtyping.
There are a number of ways Java allows subtyping:
class A extends B
, A
is a subtype of B
because B b = new A(...);
is ok.interface A extends B
, A
is a subtype of B
because B b = new A() { ... }
is ok.class A extends B
, A[]
is a subtype of B[]
because B[] b = new A[0]
is ok.class A implements B
, A
is a subtype of B
because B b = new A(...)
is ok.It sounds like you want a way to distinguish one from the others. The below should do that.
static boolean isSubclass(Class<?> a, Class<?> b) {
return !b.isArray() && !b.isInterface() && b.isAssignableFrom(a);
}
It won't handle subtyping of generic classes due to type erasure though. Class
instances don't carry type parameters at runtime so there is no way to distinguish the runtime type of a new ArrayList<String>()
from a new ArrayList<Integer>()
.
In general, subclassing means to inherit the attributes of a parent. Subtyping merely means that operations on the supertype can be performed on the subtype. Note that subclassing is a special case of subtyping.
in Java, interfaces represent the structure for describing what behaviors a type can exhibit, which makes it the natural representation for subtyping. Subclassing is manifested in the class hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With