简体   繁体   English

Java泛型类

[英]Java generic classes

I understand that in the fields of a class, you can make the field type the name of another class and then in the constructor initialise that field by calling a new class of that type, ie我知道在类的字段中,您可以使字段类型成为另一个类的名称,然后在构造函数中通过调用该类型的新类来初始化该字段,即

public class Auction {
    private Bid bid;
}
public Auction {
    bid = new Bid();
}

The main reason for doing this is, as I understand it, to access the methods of that class.据我所知,这样做的主要原因是访问该类的方法。

My question is I've noticed in some methods that there are local variables created that have a type of a different class with a variable name.我的问题是我注意到在某些方法中创建了具有变量名称的不同类的类型的局部变量。 What is the purpose of assigning a local variable name with a type of another class?用另一个类的类型分配局部变量名称的目的是什么? Is this another way of just accessing those methods directly, even if it hasn't been done in the fields or constructor?这是另一种直接访问这些方法的方法,即使它没有在字段或构造函数中完成?

You can do this assignment only if type of the right part is-a type of the left part.仅当右侧部分类型是左侧部分类型时,您才能进行此分配。 So, for example, you can use methods of left part' type with realization from right part' type.因此,例如,您可以使用 left part' 类型的方法与 right part' 类型的实现。

Number number = new Integer(10);

See also OOP in Java and Polymorphism in Java .另请参阅Java 中的 OOP 和 Java 中的多态性

First of all, you need to learn some basics about OOP.首先,您需要了解一些有关 OOP 的基础知识。 We use Objects to model the problems and solve them in Object Oriented Programming.我们使用Objects对问题进行建模并在面向对象编程中解决它们。

These "type of a different class with a variable name" is an instance of a class, which is called an Object .这些“具有变量名称的不同类的类型”是类的实例,称为Object We can assign a variable name to an object in order to use that object and its behaviors.我们可以为一个对象分配一个变量名,以便使用该对象及其行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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