How to access private variables in a Java class method [closed] - java

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to access a private variable (x) in my method distanceFromPoint but it seems it doesn't work. How can I access it? My method is returning 0.0 all the time regardless of other values.
Code
public class Pointdeclare {
private static int x;
private static int y;
Pointdeclare (int x_ , int y_ ){
this.x = x_;
this.y = y_;
}
int getX(){
return x;
}
int getY(){
return y;
}
static double distanceFromZero (){
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
double distanceFromPoint(Pointdeclare point){
int distX = point.getX()- this.x;
int distY = point.getY()- this.y;
return (double) Math.sqrt(Math.pow(distX, 2) + Math.pow(distY, 2));
}
}
Main Class
public class main {
static Pointdeclare p1 = new Pointdeclare(6, 7);
static Pointdeclare p2 = new Pointdeclare(3, 7);
public static void main (String[] args){
System.out.println(p2.distanceFromZero());
System.out.print(p1.distanceFromPoint(p2));
}
}

This will work better for you:
package cruft;
/**
* Point2 description here
* #author Michael
* #link http://stackoverflow.com/questions/14087002/how-to-access-private-variables-in-a-java-class-method
* #since 12/29/12 6:52 PM
*/
public class Point2 {
private int x;
private int y;
Point2(int x_, int y_) {
this.x = x_;
this.y = y_;
}
int getX() {
return x;
}
int getY() {
return y;
}
double distanceFromZero() {
return distanceFromPoint(new Point2(0, 0));
}
double distanceFromPoint(Point2 point) {
int distX = point.getX()-this.x;
int distY = point.getY()-this.y;
return (double) Math.sqrt(Math.pow(distX, 2)+Math.pow(distY, 2));
}
public static void main(String[] args) {
Point2 p1 = new Point2(6, 7);
Point2 p2 = new Point2(3, 7);
System.out.println(p2.distanceFromZero());
System.out.print(p1.distanceFromPoint(p2));
}
}

You shouldn't declare your class fields as static, just leave them private.
Btw consider using Point or Point2D native classes from java.awt.geom package.

You declared "x" and "y" static, which means that they're class variables, not instance variables.
Because of that, every new call to the constructor will overwrite the old values. Thus distanceFromPoint always returns zero because there's only one x and one y.

The problem is not due to private, instead, it's because of static. x is static. In your method, you should use x as:
int distX = point.getX()- Pointdeclare.x; // You could use this.x because x is static.

I hope you find this relevant, it doesn't answer your question directly but I was recently informed my understanding of static was incorrect so having just researched the topic I thought maybe I could help. Static variables belong to a class and not its objects, objects of a class may access a static variable but no matter how many objects of the class there are there will only be one copy of the static variable. So I think what the people before me were saying is instead of p1 and p2 having their own copies of x and y both objects share the same x and y field therefore your value returned is 0. In other worlds your trying to find the distance between one location, it will always be zero. Hopefully that helps :-). I'm sorry I missed the first line of the main method. p2 should return a value as long as it isn't zero but p1 will not.

Related

call a method in class, inheritance

I have a problem, the solution is probably very easy, but nothing comes to mind at the moment, so I am looking for a little help.
... so I have a problem with calling the method.
I have a Space 2D class:
public class Space2D {
//several other methods etc.
//for example I will take this method
public double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
and I want to call it in the SpaceTest class:
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D point2D = new Space2D();
// I also have a Space 3D class that inherits from the 2D class.
// but I want to call the distance method from the Space 2D class so I'll try to do it like this:
point2D.distance(3,4) // <-- wrong
}
}
I would like to put 3 and 4 after p1 and p2 from the distance method but I get a bug that I have to put integers in it if I want to do so, so my question what do I have to put in calling this method so that I can run it, i.e. what do I have to put for this object ?? "Space2D p1"?
point2D.distance (???)
Thank you in advance for your help and explanation, I hope you will help me understand this.
public double distance(Space2D p1, Space2D p2) {
...
This means when you invoke distance you have to pass in two objects of type Space2D.
point2D.distance(3,4) <-- wrong
You tried to invoke it with two integers, which is why you get the error. Points have an x and y coordinate, what does it even mean to ask for the distance between 3 and 4 if the domain is R2.
What you probably want is something like
int dist = point2d.distance(new Point2D(3,0), new Point2D(4,0));
That's because you're putting integers as parameter which is not allowing to take as parameter. Distance function takes distance(Space2D p1, Space2D p2) Space2D object.
You can use like this:
In Space2D Class :
public class Space2D {
private int x;
private int y;
public Space2D(int x, int y) {
this.x = x;
this.y = y;
}
//several other methods etc.
//for example I will take this method
public static double distance(Space2D p1, Space2D p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
}
In SpaceTest class :
public class SpaceTest extends Space3D {
public static void main(String[] args) {
Space2D.distance(new Space2D(3, 2), new Space2D(3, 2));
}
}

How to make a class operate with math operation in java? [duplicate]

This question already has answers here:
Operator overloading in Java
(10 answers)
Closed 5 years ago.
I have the following class, which describe one point on XY surface:
class Point{
double x;
double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
So I want to overlad + and - operators to have possibility write run following code:
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point resAdd = p1 + p2; // answer (4, 6)
Point resSub = p1 - p2; // answer (-2, -2)
How can I do it in Java? Or I should use methods like this:
public Point Add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y);
}
Thanks in advance!
You cannot do this in Java. You'd have to implement a plus or add method in your Point class.
class Point{
public double x;
public double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public Point add(Point other){
this.x += other.x;
this.y += other.y;
return this;
}
}
usage
Point a = new Point(1,1);
Point b = new Point(2,2);
a.add(b); //=> (3,3)
// because method returns point, you can chain `add` calls
// e.g., a.add(b).add(c)
Despite you can't do it in pure java you can do it using java-oo compiler plugin.
You need to write add method for + operator:
public Point add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
and java-oo plugin just desugar operators to these method calls.
There is no operator overloading in Java. Apparently for reasons of taste. Pity really.
(Some people will claim that Java does have overloading, because of + with String and perhaps autoboxing/unboxing.)
Let's talk about value types.
Many early classes (and some later ones) make a right mess of this. Particularly in AWT. In AWT you should be explicitly making copies of simple values all over the place. Almost certainly you want to make value types immutable - the class should be final and it should never change state (generally all final fields pointing to effective immutables).
So:
public final class Point {
private final int x;
private final int y;
private Point(int x, int y) {
this.x = x;
this.y = y;
}
public static of(int x, int y) {
return new Point(x, y);
}
public int x() {
return x;
}
public int y() {
return y;
}
public Point add(Point other) {
return of(x+other.x, y+other.y);
}
// Standard fluffy bits:
#Override public int hashCode() {
return x + 37*y;
}
#Override public boolean equals(Object obj) {
if (!(obj instanceof Point)) {
return false;
}
Point other = (Point)obj;
return x==other.x && y==other.y;
}
#Override public String toString() {
return "("+x+", "+y+")";
}
}
The original code was confused between int and double, so I've chosen one. If you used double you should exclude NaN. "Point" tends to imply an absolute point, which doesn't make sense to add. "Vector" or "dimension" would probably be more appropriate, depending upon what you intend.
I've hidden the constructor, as identity is not important. Possibly values could be cached. Possibly it is, say, common to add a point to a zero point, so no points need to be created.
It's possible you might want a mutable version, for example to use as an accumulator. This should be a separate class without an inheritance relationship. Probably not in simple cases, but I'll show it anyway:
public final class PointBuilder {
private int x;
private int y;
public PointBuilder() {
}
public PointBuilder(Point point) {
this.x = point.x;
this.y = point.y;
}
public Point toPoint() {
return new Point(x, y);
}
public PointBuilder x(int x) {
this.x = x;
return this;
}
public PointBuilder y(int y) {
this.y = y;
return this;
}
public PointBuilder add(Point other) {
this.x += other.x;
this.y += other.y;
return this;
}
}
You cannot do this in Java because there is no operator overloading in Java.
You have to use the second option you have mentioned:
Edit: You can add the Add method in the Point class itself
public Point Add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
You cannot overload operators in java. You will need handle this in Point class.
You cannot override operators in Java. That's one of the reasons why any nontrival math (especially geometric) operations should not be implemented in Java (the Point class above is kind of such a class, if you want it to do some real work, for example a line-line intersection, you'd better do it in C++).

How can I print multiple class instances in one statement? Java

public Class Point{
private double x;
private double y;
public Point() {
super();
}
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
public static Point deepCopy(Point p2) {
Point point2 = new Point(p2.x+2, p2.y+2);
return point2;
}
public static Point shallowCopy(Point p4){
return p4;
}
public void setPoint3X(double x3) {
this.x = x+1;
}
public void setPoint3Y(double y3) {
this.y = y+1;
}
public void setPoint2(double x2, double y2) {
this.x = x2+2;
this.y = y2+2;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
public class PointDemo {
public static void main(String[] args) {
double x = 0;
double y = 0;
Point point1 = new Point(5, 10);
Point point2 = Point.deepCopy(point1);
Point point3 = Point.deepCopy(point2);
point3.setPoint3X(x);
point3.setPoint3Y(y);
Point point4 = new Point();
point4 = Point.shallowCopy(point3);
Question 4 -
Write a class called Point. The class has two instance fields: x and y, both are of double type.
Write two constructors: one that uses x and y values for a point, and the other uses the first point values to create a second Point object with the exact same x and y values. Write a Demo class to build the following four Point objects.
Point 1: (x=5, y=10)
Point 2: (x=7, x=12). This point needs to be built using the deep copy constructor that copies point 1 and then using only one setter method.
Point 3: (x=10, y=15). This point needs to be built using the deep copy method that uses Point 2 as the original and then using two setter methods to change the required x and y values.
Point 4: This point needs to be built using the shallow copy method and it must use Point 3 as the shallow copy template.
Finally print all four points using one statement.
Okay. So my code gives me all the values from point1-point4 however, I cannot figure out a way to print them all in one statement. Obviously a loop in the demo class can print every Point object but that would be multiple print statements which violates the one print statement requirement.
Also, I cannot use an array in the Point class because it violates the 2 fields requirement.
Can anybody help or give me a suggestion as to how I can take all the Point objects and print it in one statement? Or is that even possible and maybe I am reading the question wrong?
You can use PrintStream.format(format(String format, Object... args):
System.out.format("(%f, %f), (%f, %f), (%f, %f), (%f, %f)\n", point1.x, point1.y, point2.x, point2.y, ...and so on);
I'm going to post this as an answer too since I think it might be what your instructor actually wants.
The key point here is to remember that the toString() method on your class can be used like a regular string and concatenate other strings, and that's what you normally do with + when calling println(). So just use the normal println() method like you've probably been doing already.
System.out.println( "Point 1 - " + point1.toString() + ";\n"
+ "Point 2 - " + point2.toString() + ";\n"
+ "Point 3 - " + point3.toString() + ";\n"
+ "Point 4 - " + point4.toString() + ";" );
You can use streams:
Arrays.stream(new Point[] {point1, point2, point3, point4}).forEach(System.out::println);
or String.format()
System.out::println(String.format("%s %s %s %s", point1, point2, point3, point4));

New Instances of Objects Set to Identical Values

public class TriVal {
private static int x;
private static int y;
private static int z;
TriVal(int x, int y, int z) {
TriVal.x = x;
TriVal.y = y;
TriVal.z = z;
}
public int sum(TriVal p2) {
int a = Math.abs(TriVal.x + p2.x);
int b = Math.abs(TriVal.y + p2.y);
int c = Math.abs(TriVal.z + p3.z);
int sum = a + b + c;
return sum;
}
}
This is a piece of a constructor for an object that contains a set of 3 values.
However, I am writing a function that creates a new TriVal made by summing the x, y, and z, of two instances of this object.
So say we have
TriVal p1 = new TriVal(10, 10, 10);
TriVal p2 = new TriVal(20, 20, 20);
calling the function
p1.sum(p2)
(Which is included elsewhere in the class) should return 90.
However, it returns 120.
I am learning that upon creating a new instance of the TriVal Object, the previously defined p1 instance is somehow being set to the same values as p2, which explains the sum being 120.
I believe this error is located somewhere in my constructor, perhaps in the way I am updating values or declaring variables at the top of the class?
Any helpful tips would be appreciated, thank you!
private static int x;
private static int y;
private static int z;
You declared your instance member as static which will be same for all the instances. They store last assigned values. remove static and you'll be fine.
As #Orin pointed, you'll need to change the code a bit where you should bind your parameters to instance members.

Array overwriting all other values when a new one is added

I have been having an issue when adding objects to an array. It seems that every single time I add a new WoodFloor object to the array, it overwrites all of the other values of the array. Here's my code:
package code;
public class Main {
private static Block[] blocks = new Block[12];
public static void main(String[] args) {
for(int i = 0; i < 12; i++) {
blocks[i] = new WoodFloor(i * 10, i * 20);
}
}
}
package code;
public class Block {
protected static int x, y;
public Block(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
package code;
public final class WoodFloor extends Block {
public WoodFloor(int x, int y) {
super(x, y);
}
}
Don't use static modifier for class fields that need to be different for each instance. The static modifier makes the field a class field, one that is effectively shared by all instances, and this is not what you want.
So change this:
protected static int x, y;
to this:
protected int x, y;
Your program produces 12 different objects, but they all reference the same pair of x and y. The problem is on this line:
protected static int x, y;
// ^^^^^^
When you make a field static, you are saying that the value of this field is going to be the same in every single object of the class. This is definitely not what you are trying to achieve here: you need each WoodFloor to have its own x and y. For that, you use instance fields (i.e. fields declared without static).
Static makes the variable available at the class lever so an instance is not needed to access it. Here effectively resets it to its original value each time rather than moving to the next array position and forgets the old array.
I'm suspecting it's the 'static' keyword for x and y.

Categories

Resources