java - Using an instance variable of an object in a different class -
i made object called 1 using shape class, , called instance variable x1 'one', , set int x doing int x = one.x1; , works fine. when tried in different class, doesn't work @ all. when tried in different class error message shows said "one cannot resolve variable." if know what's wrong, , how fix this, please let me know. thank you.
package events; public class shape { int x1; int x2; int y1; int y2; int width; int height; shape(int x1, int y1, int width, int height) { this.x1 = x1; this.y1 = y1; this.width = width; this.height = height; this.x2 = x1 + width; this.y2 = y1 + height; } public static void main(string[] args){ shape 1 = new shape(4,4,4,4); int x = one.x1; } } the codes doesn't work:
package events; public class test { public static void main(string[] args){ int x = one.x1; } }
you have set variables public public int x1; if want access them externally.
however practice use getters , setters instead:
//things private int x1; //more stuff public int getx1(){ return x1; } public void setx1(int x){ x1 = x; } edit:
appears i've missed point of question, answer it, cannot access variable outside of defined. if want use one somewhere else, have either create setter it, or define in broader scope.
if must, recommend doing show above, define private shape one; set in main one = new shape(...) , add getter public shape getone(){...}
then in test class can call getone() , access variables.
Comments
Post a Comment