简体   繁体   English

为什么在定义类之前要声明嵌套类的变量

[英]Why can we declare a variable of a nested class before defining the class

For example, 例如,

public class Stack<Item> implements Iterable<Item>
{
 private Node first; // top of stack (most recently added node)
 private int N;      // number of items
 private class Node
 {  // nested class to define nodes
  Item item;
  Node next; 
 }

Why can we declare first to be of type Node before defining what Node is. 为什么我们在定义什么是Node之前先声明其类型为Node。 Also, as an extension, why are instance variables always declared first. 另外,作为扩展,为什么总是总是首先声明实例变量。 What happens if we define some instance variables, then some methods, then more instance variables, and more methods. 如果我们定义一些实例变量,然后一些方法,然后更多的实例变量和更多的方法,将会发生什么。

Because there is no attempt at resolution until the entire class has been parsed. 因为在解析完整个类之前才尝试进行解析。 For the same reason, you can call class methods that haven't been defined yet. 出于相同的原因,您可以调用尚未定义的类方法。

Instance variable are not always declared first. 实例变量并非总是先声明。 You can declare things in any order you like, subject only to initialization order constraints. 您可以按照自己喜欢的任何顺序声明事物,仅需遵守初始化顺序约束即可。

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

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