Instantiate 'this' Object - java

I'm trying to load a serialized object within the class using a method like this one:
private void loadCatalog(MyClass myClassNew)
{
this = myClassNew;
}
So I have this method in my MyClass, and I receive as a parameter an object having the type of MyClass. How can I do something like above? The code above gives me an error of which I'm not sure why. The object myClassNew is the same as the one before serializing, so I'm sure that I receive a valid object of type MyClass.

There is no way to do that. You must write code that copies each instance field of MyClass from the argument to this. For instance:
this.firstName = myClassNew.firstName;
this.lastName = myClassNew.lastName;
You could use reflection do to this, but you probably shouldn’t. Unless MyClass is very simple, you may find that some fields require special handling. For example, copying a List reference would be very bad, unless it’s an unmodifable List, as the two objects should share a reference to the same List object.

You will get an error:
The left-hand side of an assignment must be a variable
"this" is not a variable that you can assign to. you can create fields in the object and do "this.field1 = myClassNew", but you cannot assign to "this".

Related

How does ArrayList.get return its objects?

Context: I'm making a mini-interpreter-ish calculator thing. I figured that the best way to hold the symbol table was to make an ArrayList of an Object that I've defined (name of the object is WiP). Setting up the ArrayList looks like.
ArrayList<miniVariable> vList = new ArrayList<miniVariable>();
Simple enough, and the miniVariable Object contains the following variables
public String name;
public double value;
public boolean initialized;
They are public because I already made setter/getters in the class with the ArrayList, when I didn't realize you could make one of Objects, and I don't want to move everything over. I probably should.
Question: If I were to call vList.get(index) .value = 5; would it actually change the value being stored in the vList(index)'s value variable? Or does .get(index)just return a copy of the data, and so changing this copy doesn't actually do anything?
It changes the value on the original instance, as one would expect.
Creating a copy of an object in Java only happens explicitly (and usually with some difficulty at that).
A few other notes:
Class names in should be CapitalCase.
Implementing getters and setters on an object holding a list of objects is bad practice as it violates encapsulation. If you're implementing getters and setters, it's best to put them on the class they apply to.
What you are storing in the ArrayList is not the object itself, but reference to object.
So when you do vList.get(i) it is returning you the reference that you previous put in. Which means you are going to access the same object that you previous put in the list, instead of a copy of it.
Get yourself familiar with one of the basic concept of Java, which is Reference and Primitive types.
Some off-topic suggestions:
Make sure you are aware of Java's naming convention. For example, for the class name, it should be MiniVariable instead of miniVariable.
Just to be more accurate: "and the miniVariable Object contains the following variable", MiniVariable is a class, but not an object. You may say "and a MiniVariable object (instance) contains these member fields", or "in MiniVariable class defined the following member fields"
All collections objects stores reference to object , if you change any thing on object directly(accessing through collection) or indirectly ( already have reference of it) it will change the state of the object stored in collection

Safeguarding method parameters in java

I want to safe guard my method parameters that were passed to the called method from being changed accidentally. I know that we can use final keyword to achieve this (partially) like the following in the method signature.
public void someMethod(final int intVal, final MyClass myobj){}
With the help of the above signature I cannot change the value of intVal, but however I can change the values (members) of myobj (I can safe guard only the reference not being changed, but not the members of the referencing object, that why I said partial).
Now I am looking to safe guard my myobj members either, getting changed in the called method someMethod.
In my knowledge I could achieve this using the following ways
Create an immutable class and pass it as a parameter
Deep copy the object and send the cloned object to the method.
Is there any better apporach to safeguard the method parameters?

Get Class representing the class that declares a field

If I'm only given a field instance from a class, without further knowledge about the class that declares that field, is it possible to get an instance of the declaring (outer) class?
For instance, consider the following class structure.
class A {
static final Tclass t = Tclass.create();
}
Now, in some other function, we are only given t (Tclass instance). Is it possible to use reflection in some way to grab the outer/declaring class (class A) that holds t?
I don't think the statement given t means what you think it means.
If you mean you do something like
someMethod(t);
and you want someMethod to get a reference back to A, you're out of luck. When used in an expression like that, the expression t resolves to a value. That value is a reference to an object. Such a reference is one-way only. someMethod has absolutely no knowledge about the existence of a static variable t.
If you mean you have a Field instance for t, you can simply call Field#getDeclaringClass() to get the declaring class.

right way to pass objects in another object

Good morning, i'm learning java and i have a question.
I have a class "table" with a constructor, that accept a "fields", and put it in PRIVATE variable.
the question is: it is right to pass the object and use a "=" to put in the PRIVATE variable, or it's better to clone it?
if i use a "=", the variable inside my class are still editable from the method that used the constructor of the class, and eventually put NULL inside it.
for example:
class Table{
private Field field;
table (Field field)
{this.field=field;}
public String getValue()
{return field.toString(); }
}
main{
Field field=new Field("VALUE1");
Table table(field);
field.value="VALUE2";
System.out.println(table.field.getValue());
}
and the result is "VALUE2".
So in the table passed a value, and then i alter it.
but for the "good programming art", it is acceptable, or is better
class Table{
private Field field;
table (Field field)
{this.field=field.clone();}
public String getValue()
{return field.toString();}
}
main{
Field field=new Field("VALUE1");
Table table(field);
field.value="VALUE2";
System.out.println(table.field.getValue());
}
prints VALUE1
so if i pass a value to a Table, i can't modify it without using the Table methods?
what is the right way to to this?
This is a good question and points to a real problem. The recommended way to do this would be to have your classes immutable.
So the problem is not in the Table class, but in the Field class - it should only allow the modification of the value through the constructor, not through direct changes or with setters. Doing that you won't have this issue.
Declaring a variable private has nothing to do with its immutability. If the object passed to you is not immutable then I would suggest making a (deep) copy, otherwise you cannot rely on it not being changed elsewhere.
Other way would be making the Field class immutable, then you wouldn't have to make a copy, you would just save the reference in a private field.
There is no right or wrong way to do this in Java. Java passes objects by reference, and you need to understand that objects passed by reference are usually mutable, meaning they can change state. In Java, this is the expected behavior, but it can be confusing at first. It can also be very difficult to manage in a multi-threaded environment.
You do have the option, as #eis has indicated, to use immutable objects. There are many advantages to this, especially in multi-threaded code, but also some disadvantages. That discussion is too long and involved to get into here.
If you are concerned specifically with Java collections, the collections framework allows you to make a collection immutable. See the java.util.Collections.unmodifiable* methods for details on how to do that. Those methods can make an unmodifiable view of a collection without the overhead of cloning the data.
When you want the second object to see your original object over its lifetime, no matter how you change it, clone it before you pass it, or use an immutable object in the first place. When you want to ensure the second object cannot change your object, make it either immutable or use a read-only view as the Java collections do.
Good morning to you too.
I guess that you already know that Java is pass by reference value, so in the first case, table.field and field are "pointers" to the same object. Thus, modifying one will modify the other and viceversa. If that is what you want in this case then your first implementation would be correct.
On the other hand, if you just want to pass an object and you wouldn't be using the object field that you created, the following would be better suited:
Table table(new Field("Value 1"));
Lastly, if you just want to pass the value and you field and table.field referencing different objects that happen to have the same value. Modifying one won't modify the other. The clone() method is a valid solution, but not all classes implement this method. If the class Field didn't support the method clone(), your best bet is to implement a method similar to this in the Field class:
class Field {
//...Your code...
//First possibility
public void copyField(Field originalField) {
this.atribute1 = originalField.attribute1;
this.atribute2 = originalField.attribute2;
//This way you copy all the attributes manually
}
//Second possibility (a static method)
public static void copyField(Field newField, Field originalField) {
newField.atribute1 = originalField.attribute1;
newField.atribute2 = originalField.attribute2;
//This way you copy all the attributes manually
}
}
//**Using each method to make a copy of field1 in field2**
Field field1 = new Field(...);
Field field2 = new Field();
field2.copyField(field1); //Non-static method
Field.copyField(field1, field2); //Static method
Yet another solution would be to make a copy constructor which would be almost exactly the same as the non-static method:
public Field(Field fieldToCopy) {
this.atribute1 = fieldToCopy.attribute1;
this.atribute2 = fieldToCopy.attribute2;
//...
}
As you can see there are several correct ways to do this. You need to be able to chose and implement any of them depending on the particular problem you are solving.

modify value in variable

I have a problem with one class in java
this class is public and extends of DefaultHandler
all method of this class are public too ... but the variables are private...
My problem is that if I copy the value in other variable and modify this second variable the first change too.
is like static variables.. but they are no static... any idea!!!
thanks in advance
This is because you are actually modifying the same object. For instance, if you have
Object obj = new Object();
Object obj2 = obj;
You don't actually copy anything, you simply make obj2 "point" (not quite the right term, but it will work for now) to obj. Any changes to obj2 will be reflected in obj. Therefore, if you want to actually copy it, you need to physically create a new Object and then manually copy all of the values into the new creation. You could implement the prototype pattern to copy the object. Primitives don't behave this way so if you were to do the same thing with a double or an int for instance, it would behave the way you expect.
Does all of that make sense?
You are probably having a problem with passing by reference versus passing by value. This page explains what I mean http://www.cs.umd.edu/class/sum2004/cmsc420/sum4v3e01/node6.html.
You probably are copying a reference to a changeable object, not the object itself; so after the copy, you have two references to the same object. Changing that object through either reference will have the same effect.
I can't tell you how to copy the actual object because there's no generic way to do it, but many classes provide a copy constructor or some other way to duplicate themselves. If you need help with that you'd have to provide more details.

Categories