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;
}
}
Related
#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).
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...
public static int multiply(int a, int b) {
int product = a * b;
return product;
}
I am trying to write a J Unit test for this code. Right now it passes, but I am not fully sure if I have it correct. I am also not fully sure if the code is correct to begin with. The code is suppose to take two rational numbers as parameters and return a Rational number as their product.
#Test
public void multiplyTest() {
int product = Rational.multiply(5/7,2/3);
assertEquals(product, Rational.multiply(5/7, 2/3));
}
Update
Here is my Rational class with my actual code:
public class Rational {
private int num;
private int den;
public Rational(int numIn, int denIn) {
num = numIn;
den = denIn;
}
public int getNum() {
return num;
}
public int getDen() {
return den;
}
public String toString() {
return num + "/" + den;
}
public String reciprocal() {
return den + "/" + num;
}
public static int multiply(int a, int b) {
int product = a * b;
return product;
}
public int divide(int a) {
int number = num / den;
return number / a;
}
public int add(int number) {
int sum = ((this.num * den) + (num * this.den)) / (this.den * den);
return sum;
}
}
The solution is not correct nor is the test.
Your method takes as inputs two integers and returns an integer.
You need to create a Rational class with nominator and denominator fields.
Use it as the type of arguments and return type.
Also you need to tell the result to the test which is 10/21 and the test will determine if the method under test can get the correct result . The given junit uses the same method to calculate the same thing twice and then verifies that the results are the same. They are of course the same but this proves nothing.
Update
Based on your update I provide an updated version of your Rational class.
Similar changes can be done to the other methods. Notice that it would be better for reciprocal to return a rational so that the programmer can also use it.
You can still print it by writting rational.reciprocal() as toString will be automatically called for example in System.out.println(rational.reciprocal());
public class Rational {
private final int num;
private final int den;
public Rational(int numIn, int denIn) {
num = numIn;
den = denIn;
}
public int getNum() {
return num;
}
public int getDen() {
return den;
}
public String toString() {
return num + "/" + den;
}
public Rational reciprocal() {
return new Rational(den,num);
}
public static Rational multiply(Rational a, Rational b) {
return new Rational(a.num * b.num , a.den * b.den );
}
public Rational divide(int a) {
return new Rational(this.num,a*this.den);
}
}
Your code just calls the code under test twice. That would test that multiply is idempotent (at least when called twice). It does not test that it actually multiplies its parameters. If it just added them and returned the sum, your test would not notice (i.e., fail).
Your test is also quite complicated; why the division in the code?
Do something like this instead:
#Test
public void multiplyInts() {
assertEquals(Integer.valueOf(35), Rational.multiply(5, 7));
}
Repeat with real or long, if that is important to your code under test.
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;
}
first i would like to start saying that i am new to programing and i don t know much. with that said i would appreciate if anyone could help me with my program that it is supposed to read 2 fractions and an operator for example "2/3 + 4/5". i have some of the code done but it still give me an error when i run it here is what i have so far:
public class Fraction {
private static int numer;
private static int denom;
public Fraction(int num, int den)
{
numer = num;
denom = den;
simplify();
}
int findGcd(int a, int b)
{
int temp;
while(b != 0)
{
temp = b;
b = a % b;
a = temp;
}
return a;
}
void simplify()
{
int gcd = findGcd(numer, denom);
numer /= gcd;
denom /= gcd;
}
public int getNumer(){
return numer;
}
public int getDenom(){
return denom;
}
Fraction add(Fraction x) {
Fraction result;
if (x.getDenom()== getDenom()) {
result = new Fraction(x.getNumer() + getNumer(), denom);
} else {
denom = this.getDenom() * x.getDenom();
numer = this.getNumer() * x.getDenom() + x.getNumer() * this.getDenom();
return new Fraction(numer,denom);
}
return result;
}
public String toString(){
return (Integer.toString(numer) + "/" +
Integer.toString(denom));
}
public static void main (String []args){
Fraction a = new Fraction(1,3);
Fraction b = new Fraction(4,5);
System.out.println(a.toString());
System.out.println(b.toString());
}
}
thank you for your help i really appreciate it.
Why are you making your fields static? static fields belong to the class as opposed to each instantiation (not what you want here). Try removing the static keyword.
On another note, you mentioned that you'd like to read input from the user. You might want to look into using a Scanner for this (in case you don't already know about this handy class).
Once you read the input, something like 2/3 + 4/5, you can split your string using a space as your delimiter. Now, you can parse a fraction from the first (2/3) and third (4/5) elements of the newly formed string array, and perform the operation that corresponds to the second element of the array (+).
There is a difference between static variable and instance variable.
Static variable is a class variable which is common for all instances.. So, if you change these variables for one instance, it will be changed for all the instances.
Instance variable, on the other hand, are specific to each instance.. They are binded to an instance of a class.
That being said.. You need to modify your code a little bit..
Change your static variables in your class to instance variables..
private static int numer;
private static int denom;
The above two variables should be instance variables.. So that they are unique for each instance you create for your class..
So, change them to: -
private int numer;
private int denom;
And for reading user input, A.R.S has already given you link to a valuable class..