Inheritance using Generics

GENERIC CLASS EXTENDING ANOTHER GENERIC CLASS :

A type argument must be passed to the type parameter of a base class. You can do so while extending the base class or while instantiating the derived class.

Examples :

1)

package com.gns.generics;

class Parcel<T> {

}

class GenericParcel<T> extends Parcel<T> {

}

public class Generic3 {
	public static void main(String[] args) {
		Parcel<String> parcel = new GenericParcel<String>();
		// Parcel<String> parcel1 = new Parcel<Integer>(); won't compile
		// Parcel<String> parcel1 = new Parcel<Object>(); wont't compile
	}

}

2)

3)

package com.gns.generics;

class Parcel<T> {

}

class GenericParcel<X,T> extends Parcel<T> {

}

public class Generic3 {
	public static void main(String[] args) {
		Parcel<String> parcel = new GenericParcel<Integer,String>();
		// Parcel<String> parcel1 = new Parcel<Integer>();
		// Parcel<String> parcel1 = new Parcel<Object>();
	}

}

4)

package com.gns.generics;

class Book{
	
}
class Parcel<T> {

}

class GenericParcel<X> extends Parcel<Book> {

}

public class Generic3 {
	public static void main(String[] args) {
		Parcel<Book> parcel = new GenericParcel<Integer>();
		// Parcel<String> parcel1 = new Parcel<Integer>();
		// Parcel<String> parcel1 = new Parcel<Object>();
	}

}

5)

package com.gns.generics;

class Parcel<T> {

}

class GenericParcel<X> extends Parcel<String> {

}

public class Generic3 {
	public static void main(String[] args) {
		Parcel<String> parcel = new GenericParcel<Integer>();
	}

}

NON-GENERIC CLASS EXTENDING A GENERIC CLASS

You can extend a generic base class to define a nongeneric base class. To do so, the derived class doesn’t define any type parameters but passes arguments to all type parameters of its generic base class. For example

package com.gs.corejava.generics;

class Phone{
	
}
class Parcel<T>{
	
}
class NonGenericPhoneParcel extends Parcel<Phone> {
	
}
public class Generic4 {

}

In the preceding example, NonGenericPhoneParcel is a nongeneric class that passes argument Phone to its base class Parcel.

You can’t pass type arguments to a nongeneric class.

Last updated