简体   繁体   English

引用另一个类的字段

[英]Referencing fields from another class

I looked all over the internet for this and I need help. 我在互联网上寻找了这个,需要帮助。

I am trying to access fields from another class using a reference I guess... 我正在尝试使用我猜的引用来访问另一类的字段...

for example: 例如:

public class Ball {
    String name;
    int size;

    public Ball(String n, int s) {
        this.name = n;
        this.size = s;
    }

Now I want to use size in another class like: 现在我想在另一个类中使用size:

public class Game {
    int length;
    int size; // same as from class Ball

Is this valid? 这有效吗? I basically want only one "size" field that can be accessed through different classes. 我基本上只希望可以通过不同的类访问一个“大小”字段。 I know this might be a very basic question but I am new to java 我知道这可能是一个非常基本的问题,但是我是Java新手

Thanks 谢谢

It seems you probably want something like the following 看来您可能想要以下内容

public class Ball {

    private int length;
    private int size;

    // getters/setters
}

public class Game {

    private int length;
    private Ball ball;

    public Game() {

    }

    public Game(int length, Ball ball) {
        this.length = length;
        this.ball = ball;
    }
}

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

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