No, you can't.
This code: Genericstring<String>
is only naming the Generic Type Variable rather than setting as java.lang.String.
The most you can do is declaring a generic type that extends a specific Class:
public class Genericstring<T extends String>
Example:
abstract class B<T extends String> {
protected T value;
public T getValue() {
return value;
}
public void handleValue() {
System.out.println(this.getValue().substring(0, 5));
}
}
class C extends B<String>{
public C() {
this.value = "Hello World";
}
}
public class A {
public static void main(String[] args) {
C obj = new C();
obj.handleValue(); // prints Hello
}
}
UPDATED: According to the comments, my answer has generated a lot of confusion because the way I've implemented.
@linuxman this is not the only way to accomplish your scenario and your right when you're mentioning Cant we mention like only B or B<T extends String>
?:
class B<T extends String> {
protected T value;
public T getValue() {
return value;
}
public void handleValue() {
System.out.println(this.getValue().substring(0, 5));
}
}
public class A {
public static void main(String[] args) {
B obj = new B<String>();
obj.handleValue();
}
}
@Pshemo is right:
In this scenario only type available for is String itself, but if it is only one type then there is no point in having a generic type because it main purse is to allow us to use our class with many types.
Also, about your doubt regarding final classes:
Reference: https://stackoverflow.com/a/5181618/1715121
A final
class is simply a class that can't be extended.
(This does not mean that all references to objects of the class would act as if they were declared as final
.)
When it's useful to declare a class as final is covered in the answers of this question:
If Java is object oriented, and you declare a class final
, doesn't it stop the idea of class having the characteristics of objects?
In some sense yes.
By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)
Related article: Java: When to create a final class
@linuxman What you're trying to accomplish doesn't make sense because the purpose of a Generic Type is to declare contracts that could implement a behavior with different types.
Hope it helps and clears your doubts.