oop - Referencing basic Java object in another class -
i'm beginner developing in java, , have run bit of problem referencing object (from different class) in class.
this code used create object, file "neighborhoods.java".
public class neighborhoods { // variables string name; int vertices; double[] latcoords; double[] longcoords; public neighborhoods() { neighborhoods fisherhill = new neighborhoods(); fisherhill.name = "fisher hill"; fisherhill.vertices = 4; fisherhill.latcoords = new double[] {42.331672, 42.326342, 42.334464, 42.335733}; fisherhill.longcoords = new double[] {-71.131277, -71.143036, -71.148615, -71.141062}; } }
i tried use object created, "fisherhill" (from class neighborhoods) in main class when calling function different class (called "inpolygon").
inpolygon.check(neighborhoods.fisherhill.vertices);
but reason, i'm getting error when try reference fisherhill object, says can't found.
i know i'm making dumb mistake here, i'm not sure is. sorry if used wrong terminology in describing code. or suggestions appreciated.
you have several things wrong in there:
neighborhoods fisherhill = new neighborhoods();
why instantiating new object of same class inside constructor? constructor called because new object of class going created. new object referenced this
. proper way initialize class fields new object:
this.name = "fisher hill"; this.vertices = 4; this.latcoords = new double[] {42.331672, 42.326342, 42.334464, 42.335733}; this.longcoords = new double[] {-71.131277, -71.143036, -71.148615, -71.141062};
as can see in other answers, this
can ommited. prefer put it, makes code more readable me.
and
inpolygon.check(neighborhoods.fisherhill.vertices);
there's no such static field neighborhoods.fisherhill
. if there, fisherhill.vertices
cannot accessed because has default accessibility.
you should create neighborhoods object, keep reference , extract vertices
field through getter:
final neighborhoods n = new neighborhoods(); final int numvertices = n.getvertices(); inpolygon.check(numvertices);
add in neighborhoods class getter vertices
field:
public int getvertices() { return this.vertices; }
i suggest java book because you're lacking knowledge of basic java , oop.
Comments
Post a Comment