简体   繁体   中英

What does generic type mean?

I have been reading my Java for Dummies book about Abstract Classes and it said this: "Abstract classes are useful when you want to create a generic type that is used as the superclass for two or more subclasses, but the superclass itself doesn't represent an actual object." You do not need to go on to explain about abstract classes, just please explain what it means by 'generic type' as I am confused as to what it means. I know nothing about generics in java, well at least I don't think I do... Please explain in SIMPLE terms, thanks :D

In Java, "Generics" are parameters for types. This may sound confusing but here is a simple explanation. If you were making a class that many other classes will inherit from, you want to make it broad and flexible. So you would use a "Generic" type to create instance variables.

Generic types can be implemented as: (Note the diamond brackets "<>")

public abstract class TestClass<T>

About Abstract Classes: In Java, if you extend a class, all methods have to be implemented, unless you declare the class abstract . If you declare the class abstract you can state methods, by putting the keyword abstract in front of their definition, and following the declaration with a semicolon. When you extend the class, you will have to implement the method with the same return type and same parameters .

Objects and Abstract Classes: You can not create an instance of an Abstract Class, because not all of the methods are developed. When creating an instance, methods will be called and the program will begin to run, however if you tried to create an instance of an Abstract Class, it would call methods with no code, Java would get confused, and the program would fail.

Creating Instances With Generics This may a little more in depth than your question, but I thought I would mention how to create an instance of a generic class.

Note the argument that goes in the diamond braces has to be an object. For primitive types, you can just use Int, Double, Float (with capital first letters) and Java will "auto-box" the objects into primitive types.

ClassName<String> obj = new ClassName<>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM