
java中嵌套结构体的替代方案
在go中,结构体可以嵌套,从而允许嵌套对象的元素冒泡到外层。在java中,类无法直接嵌套,但我们可以通过模拟来实现类似的效果。
匿名内部类
匿名内部类是模拟嵌套的一个经典方法,如下所示:
立即学习“Java免费学习笔记(深入)”;
public class outerclass {
// ...
private innerclass innerclass;
// ...
private class innerclass {
// ...
}
}继承
另一种方法是使用继承,如下所示:
class a {
// ...
}
class b extends a {
// ...
}通过继承,我们可以访问基类a的成员,并向派生类b中添加额外的成员。
使用示例
例如,让我们在java中模拟go代码中的示例:
type a struct {
ax, ay int
}
type b struct {
a
bx, by float32
}可以在java中如下模拟:
class a {
private int ax;
private int ay;
// getters and setters
}
class b extends a {
private float bx;
private float by;
// getters and setters
}然后,我们可以创建一个b对象并访问其成员:
B b = new B();
b.setAx(1);
b.setBx(3.0f);
System.out.println("Ax: " + b.getAx() + ", Bx: " + b.getBx());










