java中如何像go一样实现结构体嵌套,达到嵌套对象的元素冒泡到外层?

如下是我在go中经常用到的特性, 它可以冒泡结构体元素到上一层:

package main
import "fmt"
import "encoding/json"

type A struct {
    Ax, ay int
}
type B struct {
    A
    Bx, by float32
}
func main() {
    b := B{A{1, 2}, 3.0, 4.0}
    bytes, _ := json.Marshal(b)
    fmt.Println(string(bytes))
}

output:

{"Ax":1,"Bx":3}

这个东西有什么用?

遍历持久化数据到A上, 然后在A的基础上附加Bx属性

java我知道有匿名内部类, 但是我想知道如何做到这样的结果?

阅读 2.7k
1 个回答

Java中的类是不能直接嵌套的,不过可以模拟一下:

public class OuterClass {
    private InnerClass innerClass;
    private float Bx;
    private float by;

    public OuterClass(int Ax, int ay, float Bx, float by) {
        this.innerClass = new InnerClass(Ax, ay);
        this.Bx = Bx;
        this.by = by;
    }

    public int getAx() {
        return innerClass.getAx();
    }

    public float getBx() {
        return Bx;
    }

    private class InnerClass {
        private int Ax;
        private int ay;

        public InnerClass(int Ax, int ay) {
            this.Ax = Ax;
            this.ay = ay;
        }

        public int getAx() {
            return Ax;
        }
    }
}

用继承java里:

class A {
    public int Ax;
    private int ay;

    // getters and setters
}

class B extends A {
    public float Bx;
    private float by;

    // getters and setters
}

public class Main {
    public static void main(String[] args) {
        B b = new B();
        b.Ax = 1;
        b.Bx = 3.0f;
        System.out.println("Ax: " + b.Ax + ", Bx: " + b.Bx);
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题