我一直在阅读一些关于内部类的文档,目前正在阅读我的教科书,在那里我找到了一些关于使用内部类的很好的知识。对于初学者,我想考虑以下示例并确保我理解正确。作为引用,我已阅读以下 Inner Classes Documentation并阅读了几个 SO 问题。希望有人可以指导我完成以下操作。
import java.util.ArrayList;
public class Gearbox {
private ArrayList<Gear> gears;
private int maxGears;
private int currentGear;
public Gearbox(int maxGears)
{
this.maxGears = maxGears;
this.gears = new ArrayList<Gear>();
Gear neutral = new Gear(0,0.0);
this.gears.add(neutral);
}
public class Gear
{
private int gearNumber;
private double ratio;
public Gear(int gearNumber,double ratio)
{
this.gearNumber = gearNumber;
this.ratio = ratio;
}
public double driveSpeed(int revs){
return revs * ratio;
}
}
}
在main.java
public class Main {
public static void main(String [] args)
{
Gearbox ford = new Gearbox(6);
Gearbox.Gear first = ford.new Gear(1,20);
System.out.println(first.driveSpeed(10));
}
}
我有点困惑的是实际使用嵌套类中的一些东西的符号。例如
Gearbox ford = new Gearbox(6);
这里我们创建了一个属于Gearbox
类的ford
对象,它传入一个值6
给maxGears
.
接下来我们有 Gearbox.Gear first = ford.new Gear(1,20);
,这是我对真正发生的事情有点困惑的地方。 .Gear
是否让编译器知道 Gear
是 Gearbox
中的内部类?如果是这样,为什么下一条语句是 ford.new Gear(1,12.3)
?
像 Gearbox.Gear first = new ford.Gear(1,12.3);
这样的东西不是更有意义吗?
最佳答案
Next we have
Gearbox.Gear first = ford.new Gear(1,20);
Here is where I am kind of confused on what is really going on. Does the .Gear let the compiler know that Gear is an inner class within Gearbox?
是的......有点。实际上,它是在说“我说的是 Gearbox
中声明的 Gear
类。它不一定是内部类:它可能是嵌套类。
If so, why is the next statement
ford.new Gear(1,12.3)
?
内部类的实例必须在其封闭外部类实例的上下文中创建。 ford.new Gear(...)
表示在 ford 的
指的是。Gearbox
实例的上下文中创建新的 Gear
实例
(如果这仍然没有意义,请重新阅读上面的内容,特别注意“实例”一词的用法。类的实例是对象......)
正如@Thilo 指出的那样,在这里使 Gear
成为内部类(而不是嵌套类)并没有真正实现任何目标。将 Gear
重新声明为
public static class Gear ...
然后您就不需要使用 Gearbox
类的实例来限定 new
。
关于java - 创建内部类并使用它们(了解一些代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39177243/