问题描述
我一直在阅读我的关于抽象类的Java傻瓜书,它说:
当你想要创建一个用作两个或多个子类的超类的泛型时,抽象类很有用,但超类本身并不代表实际的对象。
您不需要继续解释抽象类,只是请解释'泛型'意味着什么,因为我对它的含义感到困惑。我对Java中的泛型一无所知,至少我不认为我这样做...
请用SIMPLE条款解释,谢谢:D
在Java中,泛型是类型的参数。这听起来可能令人困惑,但这是一个简单的解释。如果你正在创建一个其他类可以继承的类,那么你希望使它变得广泛和灵活。因此,您可以使用Generic类型来创建实例变量。
$ b
泛型类型可以实现为:(注意菱形括号<>)
public abstract class TestClass< T>
关于抽象类:
在Java中,如果扩展一个类,除非你声明类 abstract ,否则所有方法都必须实现。如果您声明了类 abstract ,则可以通过将关键字 abstract 放在其定义之前并使用分号跟随声明来声明方法。当您扩展该类时,您必须使用相同的返回类型和相同的参数实现该方法。
对象和摘要类:
您不能创建抽象类的实例,因为并非所有方法都已开发。当创建一个实例时,方法将被调用并且程序将开始运行,但是如果你尝试创建一个Abstract Class的实例,它会调用没有代码的方法,Java会变得困惑,并且程序会失败。 / p>
使用泛型创建实例这可能比您的问题深入一点,但我想我会提及如何创建泛型实例class。
请注意,钻石花括号中的论点必须是一个对象。对于原始类型,您可以使用Int,Double,Float(首字母大写),Java会将对象自动装箱到原始类型中。
的ClassName<字符串> obj = new ClassName<>();
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<>();
这篇关于泛型类型是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!