Method not storing data in object myRecipeBox [duplicate] - java

This question already has answers here:
What is variable shadowing used for in a Java class?
(5 answers)
Closed 8 years ago.
I was reading a book and came across the term Shadow Variables in Java but there was no description for it. Eventually what are these variables used for and how are they implemented?

Instead of providing my own description i may ask you to read about it for example here: http://en.wikipedia.org/wiki/Variable_shadowing. Once you understood the shadowing of variables i recommend you proceed reading about overlaying/ shadowed methods and visibility in general to get a full understanding of such terms.
Actually since the question was asked in Terms of Java here is a mini-example:
public class Shadow {
private int myIntVar = 0;
public void shadowTheVar(){
// since it has the same name as above object instance field, it shadows above
// field inside this method
int myIntVar = 5;
// If we simply refer to 'myIntVar' the one of this method is found
// (shadowing a seond one with the same name)
System.out.println(myIntVar);
// If we want to refer to the shadowed myIntVar from this class we need to
// refer to it like this:
System.out.println(this.myIntVar);
}
public static void main(String[] args){
new Shadow().shadowTheVar();
}
}

Related

Why can I access a private instance variable without a getter method? [duplicate]

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 3 years ago.
I have two objects from the same class, calling it 'first' and 'second'. I have a method that takes in an object, so I use the 'first' object, call that method, pass in the 'second' object into that method.
Inside that method, why can I access the private instance variable of the 'second' object? Am I making any sense?
// Day.java, basic example of my question
public class Day{
private int stuff = 1;
public Day(int stuff){
this.stuff = stuff;
}
public int m(Day d){ // This method takes in an object as a parameter
int add = 0;
add = this.day + d.day; // why can you do this? isn't "day" private?
return add;
}
}
Source https://www.geeksforgeeks.org/access-modifiers-java/
You are accessing it from the same class
Check this Table Out..
Because you're still accessing your variable from within the same class it belongs to.
private variables are not visible from outside the class: but they are fully visible from within the class to which they belong.
If you tried to instantiate your class inside a different class, you'd have to use a getter to gain access.

Why use "inner Class" instead of using "new" directly? [duplicate]

This question already has answers here:
What is an efficient way to implement a singleton pattern in Java? [closed]
(29 answers)
Closed 5 years ago.
When I learn guava,I found some code like this in com.google.common.hash.Hashing class:
public static HashFunction crc32c() {
return Crc32cHolder.CRC_32_C;
}
private static final class Crc32cHolder {
static final HashFunction CRC_32_C = new Crc32cHashFunction();
}
I want to know, why do not write like below, Is this merely the author's habit? or for other purpose?
public static HashFunction crc32c() {
return new Crc32cHashFunction()
}
Your alternative suggestion
public static HashFunction crc32c() {
return new Crc32cHashFunction()
}
would create a new Crc32cHashFunction instance each time crc32c() is called. If there is no specific need for a new instance to be returned by each call, it is more efficient to return the same instance in each call.
Using the static final variable
static final HashFunction CRC_32_C = new Crc32cHashFunction();
is one way to achieve a single instance.
As to why the HashFunction instance is a member of the nested class Crc32cHolder (as opposed to being a member of the outer class), the motivation is probably lazy evaluation - only at the first time the crc32c() method is called, the Crc32cHolder class would be initialized and the Crc32cHashFunction instance would be created. Thus, if that method is never called, the Crc32cHashFunction would never be created (assuming there is no other access to the Crc32cHolder class).

When to use a local access modifier? [duplicate]

This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 6 years ago.
While working in intelliJ I was recommended to make a method be localized - by removing the access modifier. I realized I don't really know which modifier to use and when and would like some clarification.
I read this post: What is the difference between Public, Private, Protected, and Nothing?
and as that's for C#, although they're similar, I wanted to make sure it's not too different.
I also read the Javadoc post here: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
and was still a bit skeptical.
Thanks in advanced!
Access modifiers help with the OOP principle of encapsulation. If you create a well-written class anyone will be able to use it without knowing all the internal details of how it works. When you define a method as public any code that uses your class will have access to that method. You only want to expose methods the end user of your class will need. If it's a helper method that's does some internal calculation relevant only inside your class, declare it as private. It will cut down on the methods available to the end user and make your class much easier to use. Here's an example:
Public Class Car {
private int speed;
private float fuelNeeded;
private float afRatio = 14.7;
public void speedUp { speed++; }
public void speedDown { speed--; }
public float getFuelNeeded {
calculateFuelNeeded(speed);
return fuelNeeded;
}
private void calculateFuelNeeded (int speed) {
// Do some complex calculation
fuelNeeded = someValue / afRatio;
}
}
Anyone who creates a Car object will have three methods available, speedUp, speedDown, and getFuelNeeded. calculateFuelNeeded is only used internally by the class, so there's no reason for the user to see it. This way they don't need to know how the amount is calculated, or when the method needs to be called, or what values it sets internally. They just get the value easily with getFuelNeeded();
When declaring variables, it is usually always correct to declare them private, having a public get() and set() method for any that need to be accessed from outside the class. The main reason for this is to prevent an outside user from setting the value something invalid. In our Car class, afRatio needs to be nonzero because we are using it as a divisor. If we declare it as public, a user could easily write this code:
Car car = new Car();
car.afRatio = 0;
someFloat = car.getFuelNeeded();
Of course this would cause our class to throw an ArithmeticException for divison by zero. However, if we did this:
private afRatio = 14.7;
public void setAfRatio(float ratio) {
if(ratio <= 0)
throw new IllegalArgumentException("A/F ratio must be greater than zero");
afRatio = ratio;
}
This allows us to check user given parameters and ensure our variables don't get set to some invalid value.

How do I initialize a Set in Java? [duplicate]

This question already has answers here:
Java default values confusion, why none for function scoped variables? [duplicate]
(3 answers)
Closed 8 years ago.
This is fine...
public class someClass {
private Set<Element> pre;
public void someMethod() {
pre.add(new Element());
}
}
But this isn't...
public class someClass {
public void someMethod() {
Set<Element> pre;
pre.add(new Element());
}
}
What's the correct syntax for the latter case without just turning it into the former?
In both cases you are missing the initialization of the Set, but in the first case it's initialized to null by default, so the code will compile, but will throw a NullPointerException when you try to add something to the Set. In the second case, the code won't even compile, since local variables must be assigned a value before being accessed.
You should fix both examples to
private Set<Element> pre = new HashSet<Element>();
and
Set<Element> pre = new HashSet<Element>();
Of course, in the second example, the Set is local to someMethod(), so there's no point in this code (you are creating a local Set which you are never using).
HashSet is one implementation of Set you can use. There are others. And if your know in advance the number of distinct elements that would be added to the Set, you can specify that number when constructing the Set. It would improve the Set's performance, since it wouldn't need to be re-sized.
private Set<Element> pre = new HashSet<Element>(someInitialSize);

Understanding Java 7 implicit method calls in Enum classes [duplicate]

This question already has answers here:
Implementing toString on Java enums
(4 answers)
Closed 8 years ago.
I'm new to Java and I'm learning the language fundamentals.
Can someone explain to me how the toString method is called when there is no function call to it? I think it has something to do with the actual enumerator words on the second line such as:
KALAMATA("Kalamata"), LIGURIO("Ligurio") ...
The whole purpose for this enum class is so the ENUM values don't print to screen in all upper case characters.
Can someone please explain me how toString method is used in this class? Like when is it called? How is it called?
public enum OliveName {
KALAMATA("Kalamata"),LIGURIO("Ligurio"),PICHOLINE("Picholine"),GOLDEN("Golden");
private String nameAsString;
//for enum classes, the constructor must be private
private OliveName(String nameAsString) {
this.nameAsString = nameAsString;
}
#Override
public String toString() {
return this.nameAsString;
}
}
Pretty much like any object.
OliveName oliveName = OliveName.KALAMATA;
System.out.println(oliveName.toString());
or
System.out.println(oliveName);

Categories