Generic Method with Lower Bound

Java-Generic Method with Lower Bound

Generic Method with Lower Bound Lower bounds are useful for cases where we want to be sure that a particular container instantiation can hold a particular element type, without limiting it to just the specific type of the element. For example, consider the following generic method: Note that T extends Comparable<T>. The Comparable is an generic interface declared … Read more…

Lower Bounds

Java-Lower Bounds

Lower Bounds Wildcard instantiations actually allow another type of bound called a lower bound as well. A lower bound is specified with the keyword super and requires that instantiations be of a certain type or any of its supertypes, up to upper bound of Type variable or Object. Consider the following classes and statement : The … Read more…

Inheritance Rules for Generic Types

Java-Inheritance Rules for Generic Types

Inheritance Rules for Generic Types When you work with generic classes, you need to learn a few rules about inheritance and subtypes. Consider the following classes and statements : The class ComputerStudent is a subclass of class Student. Is MyClass<ComputerStudent> a subclass of MyClass<Student>? Perhaps surprisingly, the answer is “no.” The third statement will not compile and it … Read more…

Implementing the Raw Type of Generic Interface

Java-Implementing the Raw Type for the Generic Interface

Implementing the Raw Type for the Generic Interface Every generic interface has a raw type. When you implement an generic interface in an ordinary class without specifying a type argument, your class is implementing the raw type, so the methods in the interface are declared with parameters and/or return types of type Object. For example … Read more…

Ambiguity Errors in Generics

Java-Ambiguity Errors in Generics

Ambiguity Errors in Generics The inclusion of generics gives rise to another type of error that you must guard against: ambiguity. Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict. Following is an example that involves method overloading : Gen declares two generic … Read more…

Generic Interfaces

Java-Generic Interfaces

Generic Interfaces Generics also work with interfaces. Thus, you can also have generic interfaces. Generic interfaces are specified just like generic classes. For example : The MyInterface is a generic interface that declares the method called myMethod( ). In general, a generic interface is declared in the same way as is a generic class. In this case, the … Read more…