Drake
Drake

Reputation: 19

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:

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

Thanks

Upvotes: 1

Views: 2995

Answers (1)

rick
rick

Reputation: 100

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;
    }
}

Upvotes: 2

Related Questions