1

Is it possible to access the variables of a object the same way you can in JS.

For example:

import java.util.*;
class Dice{
    public String [] side;
    public String name;

    public Dice (String n, String ... a){
        name = n;
        side = a;

    }

    //Setter and Getter side
    public String getSide(){
        return side;
    }
    public void setSide(String s){
        side = n;
    }

}

The array is initialized in main like so:

Dice easy = new Dice("Green:","Brain","Brain","Brain","Foot Print","Foot Print","Shotgun");

It has a name "Green".

The rest of the objects Strings are stored inside a String array.

To access the array in JS you can:

Dice.side[1];

Can we access them in Java like this, I am trying to access the array in main()?

String theStringInArray = Dice.side[1];

System.out.println(theStringInArray);

The result should print "Brain" in this example.

(This is only for myself and to gain practice I have been reading about ArrayLists but only using arrays in this example :)

Liam
  • 568
  • 2
  • 15
  • What happened when you tried? – Scott Hunter Sep 13 '19 at 15:16
  • 1
    `side` is an *instance* variable - each instance will have a separate variable. In this case, you just need `easy.side[1]` rather than `Dice.side[1]`... although I would advise against public fields in general. – Jon Skeet Sep 13 '19 at 15:16
  • @ Scott Hunte, What about this gut Scott???? https://stackoverflow.com/questions/20079681/initializing-a-dictionary-in-python-with-a-key-value-and-no-corresponding-values/20079718#20079718 – Liam Sep 13 '19 at 15:21
  • @ Jon Skeet, Thanks for the help I got the problem now it was this – Liam Sep 13 '19 at 15:27

1 Answers1

1
Dice easy = new Dice("Green:","Brain","Brain","Brain","Foot Print","Foot Print","Shotgun");

String theStringInArray = easy.side[1]; // getting the value through instance (easy)

System.out.println(theStringInArray);

If you really want to access like Dice.side[1]; you have to make side array a static variable.

public static String [] side;
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62