I worked with C# for a good six months as part of my internship. Something I learned over that internship is the beauty of C# properties, AKA setters and getters. In the beginning of the internship, properties was also a source of my confusion, but using it for awhile, I fell in love with it.
Coming back to Java for classes, I had to bid goodbye to it.
Until.. I started this simple assignment:
My methods and constructors:
private double xCoor;
private double yCoor;
public Point(double xCoor, double yCoor)
{
this.xCoor = xCoor;
this.yCoor = yCoor;
}
public void setCoor(double xCoor, double yCoor)
{
this.xCoor = xCoor;
this.yCoor = yCoor;
}
public void printCoor()
{
System.out.println("(" + xCoor + ", " + yCoor + ")");
}
For demonstration, here is my main method:
Point pointOne = new Point(6.0, 7.0);
pointOne.printCoor();
pointOne.setCoor(9.0, 3.0);
pointOne.xCoor = 9.0;
pointOne.yCoor = 7.0;
System.out.println("Java Properties: " + pointOne.xCoor);
System.out.println("Java Properties: " + pointOne.yCoor);
As you can tell, the top three lines begining with Point pointOne = ..; is the "Java" way to do things. You can see the getter which is in the form of a print statement, and the setter which is in the form of .setCoor(..).
Now, my question is, in Java (I JUST learned) - you can also set the private variables via a properties-like declaration through pointOne.xCoor = .., and of course, get them via the same way with pointOne.xCoor.
I am aware of this discrepancy with C#'s way, in that the name of the property can be manually declared, like so (if it's C#).
public string XCoor
{
get { return this.xCoor; }
set { xCoor = value; }
}
Can someone help me understand the difference between the way Java does properties and the C# way?
In java you can not set a private field from another class if there is no public getter and setter methods. Private fields without getter and setter methods can only be set and viewed within the same class.
For example
public class A {
private int a;
private int b;
private int c;
public int s;
public A(){
a=5; // In same class
b=3; // In same class
c=7;
s=9;
}
public int sum(){
return a+b; // I can access a and b directly, because we are in the same class with them.
}
public getC(){
return c; // Other classes can read value of c with this public method
}
public setC(int value){
c=value; // Other classes can set value of c with this public method
}
}
public class B{
private A obj = new A(); //
public void someMethod(){
int t = obj.getC(); // this is ok
int g = obj.s; // this is ok because s is public
int f = obj.c // compiler error, c is private, i can't see it from another class directly
int p = obj.a // compiler error, a is private, i can't see it from another class directly
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With