I've got this problem, I have a java file that obtains 2 variables from another file and is supposed to add them together and return the summed value. So far it works on obtaining the values aFirst and aSecond but I'm not sure why value one and two is lost (is back at 0) when it gets to the sum method. This is for an assignment I have for homework.
public class Pair
{
private double one, two ;
public Pair(double aFirst, double aSecond)
{
double one = aFirst;
double two = aSecond;
}
public double sum()
{
double xys = one + two;
return(xys);
}
}
You're declaring one and two as local variables, shadowing the instance variables.
the problem is the constructor. you are creating local variables and not using the class fields
private double one, two ;
public Pair(double aFirst, double aSecond)
{
this.one = aFirst;
this.two = aSecond;
}
you can do it without the "this." but dont put type ahead
Use this to access the class member variables in override cases when you have the same variable name in local scope and in the class members.
Related
In my assignment, I'm given a Food class like this:
class Food {
private String name; // name of food
private int calPerServing; // calories per serving
// must be >= 0
// min storage temperature // must be >= 0.
// max storage temperature // must be <= 100.
private float minTemp; private float maxTemp;
int getCalories() {
return calPerServing;
}
}
And I'm having trouble with this part of the assignment:
Write a constructor method for the Food class, to set the default name to "Pie", the default calPerServing to 500, the default minTemp to 25, and the default maxTemp to 75.
How do I set default values for name, calPerServing, etc.?
(I'm surprised to get to page three of search results without finding a simple version of this question to point to.)
You have two choices for setting the default value of an instance variable (sometimes called an "instance field"):
Using an initializer on the declaration.
Using an assignment in a constructor.
Say I have a class Example and an instance variable answer whose default should be 42. I can either:
// Example of #1 (initializer)
class Example {
private int answer = 42;
// ...
}
or
// Example of #2 (assignment within constructor)
class Example {
private int answer;
Example() {
this.answer = 42;
}
}
Initializers (#1) are processed during construction just before any other logic in your constructor (but after calling the superclass constructor).
Which you use depends on the class and, to an extent, personal style. If the class is going to have multiple constructors but I want answer to default to 42 regardless of which constructor is used, using initialization makes sense because then I just put it in one place instead of putting it in every constructor. If the default for answer will vary depending on which constructor is used, or depending on a parameter the constructor(s) receives/receive, setting it in the constructor makes sense.
In your specific case, the assignment tells you to use a constructor.
If you are setting default values, you simply assign a value when you declare the variable like so:
private String name = "Pie";
private int calPerServing = 500;
and so it. If you want to overwrite those variables, you can. Alternatively, you can do it in the constructor like so:
class Food {
private String name; // name of food
private int calPerServing; //
public Food(){
this.name = "Pie";
this.calPerServing = 500;
}
}
public class NotActuallyImmutable {
private final int x;
public NotActuallyImmutable(int x) {
this.x = x;// line 1
}
public int getX() {
return x;
}
}
public class Mutable extends NotActuallyImmutable {
private int x = 123;
public Mutable(int x) {
super(x);
}
public int getX() {
return x++;
}
}
now in my main class
NotActuallyImmutable n = new Mutable(42); // line2
int x = n.getX();
System.out.println("x is"+x);
I am expecting the output as 42 but it return the output as 123. I am expecting 42 because at line 2 I am making object of class Mutable and then at line 1 I am setting value as 42. so when i do n.getX() I should get the this latest value not the default 123. I know Ii am missing something but not able to figure out the logic behind it?
The problem is that the field x in Mutable and the field x in class NotActuallyImmutable are not the same. The x that is returned by getX() is the one in Mutable (because the getX() that is invoked is Mutable.getX(), not NotActuallyImmutable.getX()).
Note that if you removed the instance field from Mutable, then you would have a compiler error because NotActuallyImmutable.x is private to NotActuallyImmutable and not accessible to any code in Mutable.
If you made NotActuallyImmutable.x a protected field, then Mutable.x would shadow it and you would still have the same behavior. If you removed Mutable.x in this case, you would still have a compiler error because you were trying to increment a final field.
If you remove Mutable.getX(), then the x that would be returned by getX() would be NotActuallyImmutable.x, despite there being another field of the same name in Mutable.
The private int x in Mutable and the private int x in NotActuallyImmutable are completely different fields that just have the same name.
This isn't a problem for the compiler because you can't access a private field from another class. So as far as the compiler is concerned, when you define Mutable, the x in NotActuallyImmutable is invisible and might as well not exist.
It is of course confusing for the programmer. If you rename one of the fields to y (and the getter method to getY) the behaviour seems much more intuitive.
NotActuallyImmutable n = new Mutable(42); // line2
This means you have an object of type NotActuallyImmutable but the instance of created object is Mutable.
so in this code your dealing with Mutable object which will return 123. as the number you passed is saved in NotActuallyImmutable not in Mutable,
n has two different x values which are visible in different contexts, the parent class's private member variable and the child class's private member variable.
NotActuallyImmutable n = new Mutable(42); // line2
Creates a new Mutable. Executes parent(x) which sets the parent class's x to 42.
int x = n.getX();
n is a Mutable instance so this calls Mutable's getX() which returns Mutable's value for x (123) rather than the parent's.
I agree with Nice explanations given in above answers. But to to just brief the final understanding. As i am doing new Mutable(42).getX(), jvm first will look in Mutable object to get the value of X not inside NotActuallyImmutable. If i remove getX() method from Mutable , i get the expected(as per my expectation) value i.e 42.
This example gets messy becoz variable name i.e X is same in parent and child class but good for understanding concept
Though I'm trying to understand why "this" is needed, I'm very confused about its purpose. For instance, I coded the following:
public static void main (String args[])
{
SandboxClass1 temp = new SandboxClass1(1,2,3);
System.out.println(temp.getX());
System.out.println(temp.getY());
System.out.println(temp.getZ());
System.out.println("----------------------------");
SandboxClass1 temp2 = new SandboxClass1(4,5,6);
System.out.println(temp2.getX());
System.out.println(temp2.getY());
System.out.println(temp2.getZ());
}
public class SandboxClass1
{
private int x = 1;
private int y = 1;
private int z = 0;
public SandboxClass1(int x, int y, int zz)
{
this.x = x;
this.y = y;
z = zz;
}
public int getX()
{
return(this.x);
}
public int getY()
{
return(this.y);
}
public int getZ()
{
return(this.z);
}
}
Why do I need to code "this.z = zz"
when I could just as well write, "z = zz"?
You don't, in this case. It's only required when you must eliminate ambiguity, like when parameters and instance variables share a name.
Some people prefer to use "this" to remove conceptual ambiguity and explicitly state that the code references an instance variable.
(On a side note, the parentheses around the return values are unnecessary and a bit noisy, IMO.)
In your SandboxClass1 constructor, you have two pairs of variables each called x and y. There's the x and y declared on the object itself ("private int x = 1"), and the separate x and y that are parameters to the constructor ("int x").
The local (parameter) variable shadows the class variable. So if in the constructor you just did
x = x;
the assignment would have no effect.
The keyword this is a reference to the object that the method/constructor was called on. In the statement
this.x = x;
you're using it to assign to the other x at class level. By qualifying the name, you can tell them apart.
It's not necessary to use this with the z/zz assignment because they have different names.
It's also not necessary in the getX/Y/Z methods because there are no local variables in those methods shadowing the relevant class variables. It does no harm though.
In the SandboxClass1 constructor two of the parameters (x and y) hide class variables because they are the same name. If you want to assign the class variable x to any value while in the code>SandboxClass1 constructor, you must address it using this.x to tell the compiler that "I want to assign the class scope variable named x, and not the method scope variable named x". The same applies to y.
Since the parameter z does not hide the class scope variable named zz you do not need to tell the compiler the scope of the zz variable, the class scope zz is the only recognized variable so that is the one that gets assigned.
It has the same effect. this is needed if there is a local variable which overrides a field of the class; then you get the local variable and not the class field.
An additional advantage you can indicate the variables better. If there is a this; it's a field; local variable otherwise.
the keyword this is used to refer to an attribute that is in the class. The keyword this was created to distinguish between class attributes and method parameters. like this:
public class human
{
public void setName(String name)
{
// the first name is a reference to the class attribute name
this.name = name;
// the second name is a reference to the method parameter name
}
// definition of the class attribute name
private String name;
}
when you use the keyword this it refers to the name variable inside the class heres an example where you don't need to use this:
public class Human
{
public void setName(String myName)
{
name = myName
}
private String name;
}
see now there is only 1 variable named name and there is only one variable named myName. In the other example there was 2 variables named name. One was a class attribute and one was a method parameter.
'this' operator just refines that property/field belongs to class you're working in. It's useful whe you have, for example, two variables with the same name:
this.zz = zz;
Unlike, say, Objective-C, "this" is optional when the method or variable is local, and there is no other conflicting use of the same name.
It comes in handy in conflicting-name cases, though, such as in methods that set instance variables such as void setOnionCount(int onionCount) where you would like to use "onionCount" for the formal parameter but still have "onionCount" as the instance variable name. In such a case you can do this.onionCount = onionCount; and everyone is happy (except, I suppose, those in the Peanut Gallery who'll object to this technique).
"this" is also absolutely necessary in cases where you need to pass a reference to the current object to some other class, of course.
hey this is use to provide reference of invoking object. That i.e say suppose ur class is box then if you want to provide it's object then you can provide it within the class box using this keyword.
class Box {
int x;
public Box(int x){
this.x = x;
}
}
here in this case if your object is ob (i.e Box ob = new Box(1)) then the reference it will be passed to the itself.
Note: you cannot use this keyword outside of the class. If you use so then it will give reference of another class.
for complete detail on this keyword refer following link
http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
I have a task to operate on complex number. Each number consists of double r = real part, double i = imaginary part and String name. Name must be set within constructor, so I've created int counter, then I'm sending its value to setNextName function and get name letter back. Unfortunately incrementing this 'counter' value works only within costructor and then it is once again set to 0. How to deal with that?Some constant value? And second problem is that I also need to provide setNextNames(char c) function that will change the counter current value.
The code :
public class Imaginary {
private double re;
private double im;
private String real;
private String imaginary;
private String name;
private int counter=0;
public Imaginary(double r, double u){
re = r;
im = u;
name = this.setNextName(counter);
counter++;
}
public static String setNextName(int c){
String nameTab[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","W","V","X","Y","Z"};
String setName = nameTab[c];
System.out.println("c: "+c);
return setName;
}
public static String setNextName(char c){
//
//don't know how to deal with this part
//
}
It's hard to tell what you're doing, but I suspect this will solve your immediate problem:
private static int counter = 0;
You should make counter static.
You should also make nameTab a private static field, then in setNextName(), you can iterate through it to find the name corresponding to the given character, and get its index. (in the plain ASCII world, of course one could simply calculate the index by subtracting the numeric value of 'A' from the given character, but I am not quite sure how it would work out with Java, in Unicode, with crazy inputs - iteration is on the safe side.)
In OO languages there are typically two types of variables that go into a class:
instance variables that are unique to each instance
class variables that are shared by all instances of the class
Given a class like:
public class Person
{
// class variable
private static int numberOfEyes;
// instance variable
private String name;
// other code goes here
}
If you were to do something like:
Person a = new Person("Jane Doe");
Person b = new Person("John Doe");
and then do something like:
a.setName("Jane Foe");
the name for Person "a" would change, but the one for Person "b" would stay the same.
If you woke up one morning and decided you wanted 3 eyes:
Person.setNumberOfEyes(3);
then Person "a" and Person "b" and every other Person instance out there would suddenly have 3 eyes as well.
You want to put "static" in your counter declaration.
is your code being used by multiple threads than i would suggest that making counter static won't solve ur problem.
you need to take extra care by implementing thread synchronization use lock keyword as shown below.
private static readonly obj = new Object();
private static int counter =0;
public Imaginary(double r, double u)
{
re = r;
im = u;
lock(obj)
{
name = this.setNextName(counter);
counter++;
}
}
this will ensure thread safety also while incrementing your counter (there are another ways also to provide thread security but this one is having least code).
Because the field counter is not static, every object has its own counter.
Say I wanted to make a class to hold a set of integers that would be accessed from multiple other classes and instances. I don't want them reverting to the value they had when the code was compiled. Does that mean they have to be static, in order to keep them from going back their original value? For example
The original stats holding class here:
public class Stats() {
public static int numOne = 0;
public static int numTwo = 5;
public static int numThree = 3
//etc...
}
It is called on in two places. Here:
public class exampleClass() {
private Stats stats = new Stats();
stats.numOne += 5;
//More variable changes.
}
Also here:
public class exampleClassTwo() {
private Stats stats = new Stats();
stats.numOne -= 3;
//More variable changes.
}
Will these calls reset the variables to their original class value if the variables are not static? If so, does that mean they should always be static?
No, the variables will maintain state without the static modifier
No. You would use static key word for using those values without initializating them.
public class Stats() {
public static int numOne = 0;
public static int numTwo = 5;
public static int numThree = 3
//etc...
}
public class exampleClass() {
int a = 0;
a += Stats.numThree;
System.out.println(a);
}
>>> 3;
No need for static attributes in your case indeed, each class instance will contain a private copy of attributes initialized at instance creation time, and records all subsequent modifications until object is deleted (in java it means no longer referenced).
Main usage for static is either to store constants or global state (e.g. a singleton instance).
Doing,
private Stats stats = new Stats();
stats.numOne += 5;
Kind of defeats the purpose of having numOne as static.
The static field numOne should be accessed in a static way i.e as follows: Stats.numOne
static variables are Class variables and are used when we want to maintain a value across instances of the class. So modifying the value of numOne across various functions will keep on changing the value of class variable numOne. Run the following code to see the effect of having a class variable in a class:
public class StaticVarDemo {
public static int staticCount =0 ;
public StaticVarDemo(){
staticCount++;
}
public static void main(String[] args) {
new StaticVarDemo();
StaticVarDemo.staticCount +=5;
System.out.println("staticCount : " + StaticVarDemo.staticCount);
new StaticVarDemo();
new StaticVarDemo();
System.out.println("staticCount : "+staticCount);
}
}
It will give the output:
staticCount : 6
staticCount : 8
Yes, when you instantiate an object, variables will be initialized to the class values when they are not static.
When a variable has the static keyword, that variable value persists over all instances: the two places you called it each create an object, both objects have the same values for their static variables (even if they are changed).
Variables without the static keyword are unique to the instance: changing it on one object doesn't affect its value on the other.
See here for more info:
What does the 'static' keyword do in a class?
It seems after some research a singleton did the job. Creating one singular instance but calling on it more then once.
See Here:
http://www.tutorialspoint.com/java/java_using_singleton.htm