How to update field in java gracefully? - java

#Data
public class MyData {
private long a;
private long b;
private long c;
}
if we want to update all the field of a,b,c, then code could be like below:
MyData d;
...
d.setA(d.getA()+2);
d.setB(d.getB()+5);
d.setC(d.getAC()+8);
in other language, we may write code like:
d.a += 2;
d.b += 5;
d.c += 8;
Any graceful way to do update with this mode in java?

The other answers are all technically correct, but to give some conceptual thoughts: what you are thinking of/asking for is called Uniform Access Principle - the idea that reading and writing to a field follows the same syntax. Respectively the idea that x.y and x.y() can actually mean the same thing.
And for good or bad, Java does not support that concept on the syntactical level, and lombok doesn't help here either.
If you want to assign a value to a field, you either need an explicit setter (or maybe increment) method, or you need to make the field public.
End of story.

While you could make your fields public:
public class MyData {
public long a;
public long b;
public long c;
}
and then just
MyData d;
//...
d.a += 2;
d.b += 5;
d.c += 8;
a better approach would be to introduce increment methods:
public class MyData {
private long a;
private long b;
private long c;
public void incrementA(long x){
a += x;
}
public long incrementAndGetA(long x){
a += x;
return a;
}
public void incrementB(long x){/*...*/}
public long incrementAndGetB(long x){/*...*/}
}
and then...
MyData d;
//...
d.incrementA(2);
long bb = d.incrementAndGetB(4);
This approach will maintain encapsulation.
Obviously you can add decrement methods (or just use negative values).

you can write a function about that.
#Data
public class MyData {
private long a;
private long b;
private long c;
void add(long number1, long number2, long number3){
a += number1;
b += number2;
c += number3;
}
}
You can also use negative numbers for extraction.

You can simply create a dedicated method:
public class MyData {
private long a;
...
// use setter to set value
public void setA(long value){
this.a = value;
}
// add to current value
public void addToA(long value){
this.a += value;
}
...
}
You could also make those fields public, it comes to your choice.
But methods can do more things, like validate input values. It's also a way of encapsulating values inside of the class, and let smart methods to modify their values.
You can also modify Lombok builder to have a custom setter. You can find a thread on this here
#Builder
class MyData {
....
public static class MyDataBuilder {
public MyDataBuilder a(long value) {
this.a = value;
return this;
}
}
}

You could provide an access method
public void manipulateX(Function<Integer, Integer> manipulator) {
x = manipulator.apply (x);
}
You can then call that with mc.manipulateX(i -> i+ 2).

Related

Make a type Double behave responsively to Integer and Doubly typed assignments

I have this code:
public class doubles() {
private Double a;
public Double getA(){
return this.a
}
public void setA(Double a){
this.a = a
}
}
I want the variable 'a' to retain the properties of an integer when I do for instance
**setA(13)**
i.e a=13 and not a=13.0
Still I want variable 'a' to have the properties of a Double when I for instance
**setA(13.32)**
i.e a=13.32
Here is the small code for what you need. Please, bare in mind that I strongly advice not to follow this principle.
public class Example {
private Number a;
public Number getA() {
return a;
}
public void setA(Double a) {
if (a % 1 == 0) {
this.a = a.intValue();
} else {
this.a = a;
}
}
public void setA(int a) {
this.a = a;
}
public static void main(String[] args) {
double integerNumber = 6;
Example example = new Example();
example.setA(integerNumber);
System.out.println(example.getA());
}
}
Alternatively to using the base class Number proposed in the other answer, one can use BigDecimal: a class which stores the precision / decimal places. Hence 3.10 * 2.00 = 6.2000.
new BigDecimal("3.10").multiply(new BigDecimal("2.00"))
Disadvantage: the awkward verbosity.
Advantage: precision (called scale) and does not have the approximation errors of floating point: 3.1 = 3.100 = actually 3.099999871...

java "this" keyword proper use

I have a Fraction class using keyword this in my constructor:
public Fraction(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
adjustSigns();
if(this.denominator == 0 )
{
throw new FractionException(" Undefined Fraction ");
}
}
I also have a method :
public FractionInterface multiply(FractionInterface secondFraction)
{
Fraction second = (Fraction) secondFraction;
Fraction answer = new Fraction ((numerator * second.numerator), (denominator * second.denominator));
answer.reduceToLowestTerms();
return answer;
}
The above method works fine when I compile and run but so this this version:
public FractionInterface multiply(FractionInterface secondFraction)
{
Fraction second = (Fraction) secondFraction;
Fraction answer = new Fraction ((this.numerator * second.numerator), (this.denominator * second.denominator));
answer.reduceToLowestTerms();
return answer;
}
My question is which one is correct ?? If use the "this" keyword in my constructor do I also have to use it in my methods ?? Again, they both work fine and do what they are supposed to do but I want to know which way is the correct way. Thanks.
Using this explicitly is mandatory if you wish to distinguish between a local variable and a member of the same name. Otherwise, it is optional.
Your constructor won't assign the passes values to the instance members without the this. prefix, since the method arguments would hide the instance members. If you give the arguments different names, you can do without the this. :
public Fraction(int num, int denom)
{
numerator = num;
denominator = denom;
...
}
Both multiply versions are the same.
Both the cases you mentioned will work fine.
Use of this is a good practice as its more readable due to our english mindset, When we say this.some_variable, we get a mental image of some_variable inside the current class
this keyword is also helpful in avoiding variable shadowing
I think you have a bit of a confusion on how the "this" keyword works.
Let me give you an example:
This
public class testing {
private int a;
private int b;
testing(int a,int b){
this.a = a;
this.b = b;
}
}
is the same as:
public class testing {
private int a;
private int b;
testing(int x,int y){
this.a = x;
this.b = y;
}
}
Which of course for the second one would be easier to put if we do it like this:
public class testing {
private int a;
private int b;
testing(int x,int y){
a = x;
b = y;
}
}

Prevent Int From Being Subtracted

Is it possible to prevent an int from being subtracted from? The final keyword wouldn't work here, as I still need to be able to add to it. Thanks!
public class AddButNoSubtract {
private int i; // private
public int getI() {
return i;
}
public void incrementBy(int j) { // instead of setter
// add if positive
if (j > 0) {
// check for overflow
if (Integer.MAX_VALUE - j >= i)
this.i += j;
}
}
}
You may use Integer wrapper class instead of int as Integer class is immutable.
Another idea:
Do not expose your string as a public variable, simply provide method(s) to modify that int. And if someone tries to subtract that string then you can control that within your method.
even if you just disable the subtract then users can still add a negative number... and thus bypass your defense. a wrapper is the only thing you can use here
public class myInteger{
private int innerVal;
public int getInnerVal(){ return innerVal};
public void myInteger(int val) { innerVal = val;}
public void add(myInteger secondInt)
{
int sum = innerVal + secondInt.innerVal;
if(sum > innerVal)
{
innerVal = sum;
}
}
}
Is it possible to prevent an int from being subtracted from?
If the int variable is accessible (and not final) then No.
The only way to do this kind of thing is to make the variable inaccessible (e.g. private) and then provide methods that allow the caller what you want to happen, and forbid the things that you don't want to happen.

When to use "this" in Java

I apologize for my trivial and probably silly question, but I am a bit confused as to when to use the "this" prefix when using a method or accessing something.
For example, if we look at #4
here:
http://apcentral.collegeboard.com/apc/public/repository/ap_frq_computerscience_12.pdf
And we look at the solutions here:
http://apcentral.collegeboard.com/apc/public/repository/ap12_computer_science_a_q4.pdf
We see that one solution to part a) is
public int countWhitePixels() {
int whitePixelCount = 0;
for (int[] row : this.pixelValues) {
for (int pv : row) {
if (pv == this.WHITE) {
whitePixelCount++;
}
}
}
return whitePixelCount;
}
while another solution is
public int countWhitePixels() {
int whitePixelCount = 0;
for (int row = 0; row < pixelValues.length; row++) {
for (int col = 0; col < pixelValues[0].length; col++) {
if (pixelValues[row][col] == WHITE) {
whitePixelCount++;
}
}
}
return whitePixelCount;
}
Here is my question. Why is it that they use the "this." prefix when accessing pixelValues and even WHITE in the first solution, but not in the second? I thought "this" was implicit, so am I correct in saying "this." is NOT necessary at all for the first solution?
Thank you SO much for your help :)
With this, you explicitly refer to the object instance where you are. You can only do it in instance methods or initializer blocks, but you cannot do this in static methods or class initializer blocks.
When you need this?
Only in cases when a same-named variable (local variable or method parameter) is hiding the declaration. For example:
private int bar;
public void setBar(int bar) {
this.bar = bar;
}
Here the method parameter is hiding the instance property.
When coders used to use it?
To improve readability, it is a common practice that the programmers prepend the this. qualifier before accessing an instance property. E.g.:
public int getBar() {
return this.bar;
// return bar; // <-- this is correct, too
}
From The Java™ Tutorials
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
When the name of a method parameter is the same as one of your class data member; then, to refer to the data member, you have to put this. before it. For example, in the function setA():
public void setA(int a)
{
this.a = a;
}
Since both the data member and the papameter of the method is named a, to refer to the data member, you have to use this.a. In other cases, it's not required.
And, in your case, I don't think it's necessary to use the this, though there is no harm to use it.
this refer to the instance of the class itself. Example:
private String name, car;
public class Car(String name, String color)
{
this.name = name;
this.color = color;
}

Short hand for method and field access modifiers in a Java class?

Is there a short hand for defining the access modifiers of a classes fields and methods? More in a C++ style, I've searched but keep coming up with sites explaining what the purpose of each modifier is rather than a short hand.
public class myNum {
public int getNum() { return 0; }
public void setNum(int n) { int num = n; }
private int num;
private String value;
}
Could become
public class myNum {
public:
int getNum() { return 0; }
void setNum(int n) { int num = n; }
private:
int num;
String value;
}
For methods nope.
For variables you could try
public int n1,n2,n3..n;
private int n1,n2,n3..n;
But as you can see it can become messy quickly.
And even then, it doesn't allow for different types under one access modifier.
But really nope.
Although there is no short for defining methods, Eclipse can automatically generate getter and setter methods for you.

Categories

Resources