private instance and getter visibility in java [duplicate] - java

This question already has answers here:
Why can I access my private variables of the "other" object directly, in my equals(Object o) method
(2 answers)
Closed 8 years ago.
and thanks everyone for fixing formats etc, totally new here
I recently started learning java and one question occurred to me during one exercise, sorry if i missed posting rules:
to calculate distance from one MyPoint to another Mypoint, I decided to use a getter for MyPoint another since x and y for another should be private and can't be used on dot operation (another.x another.y);
public class MyPoint {
private int x;
private int y;
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance(MyPoint another) {
int xDiff = this.x - another.getX(); //getter
int yDiff = this.y - another.getY(); // getter
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
public class TestMyPoint {
public static void main(String[] args) {
MyPoint a = new MyPoint(3,0);
MyPoint b = new MyPoint(0,4);
System.out.println(a.distance(b)); // this works fine;
}
}
however, if i go back to the code and change another.getX() to another.x, the code still works. and same for y.
public class MyPoint {
private int x;
private int y;
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance(MyPoint another) {
int xDiff = this.x - another.x; //no getter
int yDiff = this.y - another.y; //no getter
return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
}
public class TestMyPoint {
public static void main(String[] args) {
MyPoint a = new MyPoint(3,0);
MyPoint b = new MyPoint(0,4);
System.out.println(a.distance(b)); // this still works fine;
}
}
i thought since another is a MyPoint class and instance x and y are private, there's no way for .x and .y to work, and that's the whole point of setting instance private and uses a getter.
what did i miss?

private means that the fields can only be accessed from within MyPoint. It doesn't mean that they can only be accessed from with the same instance of MyPoint. It's perfectly legitimate for methods that operate on "other" instances, especially equals and compareTo, to access private state in other instances of the same class.

Related

rectangle class in java using only 2 points

I'm writing a Rectangle class and it has 2 instance variables which are 2 points that are called _pointSW and _pointNE. I have to define the width and the height of the rectangle, but I can't use any other variables besides the 2 points.
I want to ask how I could write the getWidth() method, for example using just the _pointNE, or maybe better write a private method (because I can't use any new public methods) to define the width and the height, and then use it in other methods and if that's an option, then how do I actually write it? thanks!
If your SW means South-West and NE means North-East:
public class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
}
public class Rectangle {
private Tuple<double,double> pointSW;
private Tuple<double,double> pointNE;
public Rectangle(final Tuple<double,double> sw, final Tuple<double,double> ne) {
this.pointSW = sw;
this.pointNE = ne;
}
public double getWidth() {
return Math.abs(this.pointNE.x - this.pointSW.x);
}
public double getHeight() {
return Math.abs(this.pointSW.y - this.pointNE.y);
}
public void setWidth(final double width) {
this.pointNE.x = this.point.SW.x + width;
}
public void setHeight(final double eight) {
this.pointNE.y = this.point.SW.y + eight;
}
}

Visual Studio Code does not allow me to implement my interface(Java)

I have a project with two java files. One is the class withe the main-method and the other is a interface with two methods, which is impelemented in the Java-class and I did override the functions there.
This is my Code from the Java-Class:
public class Point implements Compare {
int y;
int x;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public void setX (int x) {
this.x = x;
}
public void setY (int y) {
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isEqualTo(Point x) {
if ((this.x == x.getX()) && (this.y == x.getY()))
return true;
else
return false;
}
public boolean isSmallerThan(Point x) {
if (this.x < x.getX())
return true;
else if (this.y < x.getY())
return true;
else
return false;
}
public static void main(String[] args) {
System.out.println("Test");
}
}
And this is the Code from my Interface:
public interface Compare {
public boolean isEqualTo();
public boolean isSmallerThan();
}
When I try to run the code i always get the following error:
Point.java:1: error: Point is not abstract and does not override abstract method isSmallerThan() in Compare
public class Point implements Compare {
^
1 error
The strange thing is now, that the same code works when i write it in project in IntelliJ IDEA.
I havent found anything on the internet yet.
ah, and i work on macOS.
Hopefully anybody can help, why the code doesnt work in VSC.
Thanks
Actually, it's not Visual Studio Code. It's a Java compiler.
It tells you "If you declared interface methods and then implementing class with this interface you have to implement them or use abstract class. The method signature should be the same."

How can I find the distance between two points using only two variables and after that store all points and obtain the shape?

I tried to declare two variable x and y, then create constructor for them and getters with setters. So, for this I used class Distance, while for the obtaining shape I need another class.
package com.company;
import java.lang.Math;
public class Point {
//fields
private int x;
private int y;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
//method
//getters
public int getX() {
return x;
}
public int getY() {
return y;
}
//setters
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getPoint(){
}
//function distance
public void distance() {
//**here I need somehow use only two variables instead of four**
double res = Math.sqrt((Math.pow(getX1(), 2) - Math.pow(getX2(), 2))
+ (Math.pow(getY1(), 2) - Math.pow(getY2(), 2)));
System.out.println(res);
}
}
Create a function that accepts object of type Point. The function returns the distance between the original point and passed point
public void distance(Point po) {
//**here I need somehow use only two variables instead of four**
double res = Math.sqrt(
Math.pow(getX() - po.getX(), 2) +
Math.pow(getY() - po.getY(), 2)
);
System.out.println(res);
}
Also your function to calculate distance was wrong.

How can I assign a value to an int variable with optional?

For example, I have got a code like this:
class Point
{
private String x;
private String y;
public String getX () { //Here can not use Optional<String>
return this.x;
}
public String getY () {
return this.y;
}
public Point(String x, String y) {
this.x = x;
this.y = y;
}
}
...
Point point = new Point(null, "14.2");
if(ofNullable(point.getX().isPresent()) {
this.xCoordinate = point.getX();
}
if(ofNullable(point.getY().isPresent()) {
this.yCoordinate = point.getY();
}
I want to do it in a cleaner way, something like this:
this.x = ofNullable(point.getX()).ifPresent((x) -> x)
I know this is not working but I tried almost everything but I can not get it to work.
You have to use Integer instead of the primitive type int
You didn't post enough code, but your getX method definition should be:
Optional<Integer> getX() instead of int getX().
If you can't modify the class with the method, create a wrapper class or something. Without seeing all the code, I can't say much more...
EDIT:
Make your point class store optional values:
class Point
{
private Optional<String> x;
private Optional<String> y;
public Optional<String> getX () { //Here can not use Optional<String>
return this.x;
}
public Optional<String> getY () {
return this.y;
}
public Point(String x, String y) {
this.x = ofNullable(x);
this.y = ofNullable(y);
}
}
Then:
Point point = new Point(null, "14.2");
if(point.getX().isPresent()) {
this.xCoordinate = point.getX();
}
if(point.getY().isPresent()) {
this.yCoordinate = point.getY();
}

Must implement abstract method

This is using Processing 3.5, not every java thing works the same here.
The Bird class is giving me the error saying it needs to implement call(). Isn't it already under the main? I'm not experienced with interfaces so I don't know what exactly is going on here.
public interface FuncCall<A> {
A call();
}
class Bird implements FuncCall{
//Error here ^
//The type FuncCallTest.Bird must implement the inherited abstract method FuncCallTest.FuncCall.call()
//Is this not implemented already under main?
float x, y, size;
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();
public Bird(float x, float y, float size){
this.x = x;
this.y = y;
this.size = size;
}
public void main(String[] args){
FuncCall<Float> getX = new FuncCall<Float>(){
#Override
public Float call(){
return x;
}
};
FuncCall<Float> getY = new FuncCall<Float>(){
#Override
public Float call(){
return y;
}
};
FuncCall<Float> getSize = new FuncCall<Float>(){
#Override
public Float call(){
return size;
}
};
inputs.add(getX);
inputs.add(getY);
inputs.add(getSize);
}
}
class Pol {
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();
public Pol(ArrayList<FuncCall<Float>> inputs){
this.inputs = inputs;
}
//public float call(ArrayList<FuncCall<Float>> arr, int index){
//return arr.get(index).call();
//}
//How do I do this? Do I need to implement the interface here as well? Because if so same error as on Bird
}
I'll also stick this extra bit on the end here.
System.out.println(pol.call(pol.inputs, 1));
Does will that work? It doesn't error before compiling.
I appreciate any help. Please ask if something doesn't make sense as I'm still new to stack and not the best with java. :)
main file :
void setup(){
Bird bird = new Bird(1.2, 3.2, 7.5);
Pol pol = new Pol(bird.inputs);
System.out.println(pol.call(pol.inputs, 1););
}
First of all you could skip your FuncCall interface and use Java's Supplier functional interface and just add these Suppliers respectively method references of your class objects getters to the list.
Another approach is to provide an interface or abstract class that has getters and/or member variables for x, y and size and use this interface or abstract class as type parameter for the list.
With Suppliers:
This is closer to your example and requires less changes in
your code.
The second option with an interface changes your Pol class
completely and I am not sure if this is acceptable for you.
´
public class Bird {
private float x;
private float y;
private float size;
public Bird(float x, float y, float size) {
//set your members here
}
public Float getX() {
return this.x;
}
public Float getY() {
return this.y;
}
public Float getSize() {
return this.size;
}
}
´
Then the Pol class
´
public class Pol {
private final List<Supplier<Float>> inputs;
public Pol(List<Supplier<Float>> inputs) {
this.inputs = inputs;
}
public Float call(int index) {
return this.inputs.get(index).get();
}
}
´
And your main should look like
´
public static int main(String[] args) {
Bird bird = new Bird(1.0f, 1.0f, 2.5f);
Pol pol = new Pol(Arrays.asList(bird::getX,
bird::getY, bird::getSize));
Float birdsSize = pol.call(2);
return 0;
}
´

Categories