I'm sitting here with an assignment that I don't quite understand - I hardly think it's that difficult, but I just don't know how to define the definition so that I make a reference to an object.
The assignment asks me to write a definition of a field named tutor that can hold a reference to an object of type Instructor.
I might not understand the question properly, but I'm fairly sure it's a rather easy assignment.
Thanks in advance.
If that's all the assignment, this is the solution:
public class MyClass{
Instructor tutor;
}
OK, when you create an object, you must have some way of holding on to it or you wouldn't be able to use it. A lot of times we define the reference and assign the value at the same time. What would happen, though, if you wanted to assign it later? Think about the typical creation of an object and what it would look like without doing the assignment, but just the definition.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.3
The answer you want is in section 4.3.1
Objects are manipulated through references in Java. To declare a variable that holds a reference you use the syntax
NameOfType nameOfVariable;
The variable can optionally be initialized with the "null" reference or with a reference to an object.
Related
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
So I'm working on with two class now and just learned to do this, yet still don't know why is this possible and what this is called. Class variable? Objects creating objects?
And in the setter method, why the default value is null? is it like String?
From what I'm assuming, 'RetailItem item' is like it combined the whole RetailItem class and creating a new variable in another class with its feature.
There are two classes named CashRegister and RetailItem.
Here goes the instance 'RetailItem item' from CashRegister with a setter.
public class CashRegister
{
private RetailItem item;
public void setItem (RetailItem newItem)
{
if (newItem != null)
{
item = newItem;
}else{
item = new RetailItem();
}
}
}
RetailItem() is a default constructor from RetailItem class.
What does item = new RetailItem(); mean?
I don't know where am I even going to start studying. What am I missing?
I have some trouble understanding your English, so I might have misinterpreted some of your questions.
What do you call this object in Java and why do you use?
I don't know which "object" you are referring to.
... yet still don't know why is this possible and what this is called.
It is just called this. There is no other term for it.
Class variable?
No. this is not a class variable.
Objects creating objects?
(Huh?) No. this is not "objects creating objects".
And in the setter method, why the default value is null?
Because that is the way that Java defined. Any instance variable (like item) whose type is a reference type has a default initial value of null.
(Why? Because that is the only value that makes sense from a language perspective. Anything else, and there would need to be some way for the programmer to say what the default is. Compilers can't read your mind!)
is it like String?
Not sure what you mean. But if you are asking if you would get the same default value behavior if item had been declared with type String, then Yes.
From what I'm assuming, RetailItem item is like it combined the whole RetailItem class and creating a new variable in another class with its feature.
Not exactly. What RetailItem item is actually doing is declaring a variable in which you may then put a reference to a RealItem object. This variable has the default value null .... until some other value is assigned to it.
What does item = new RetailItem(); mean?
That means create (construct) a new RetailItem instance (an object), and then assign its reference to the variable item.
I don't know where am I even going to start studying.
I recommend that you start with a good introductory Java textbook, or the Oracle Java Tutorial, or your course lecture notes. Ask your teachers.
But keep at it. If you work at it, you will get to the point where it all starts to make sense. Because, basic Java is a simple and consistent language. The language only gets complicated when you learn about generics, type inference / lambdas and .... multi-threading.
This question already has answers here:
Why is assignment to 'this' not allowed in java?
(7 answers)
Closed 8 years ago.
It seems a thing that almost no one has realized, but the "this reference" in Java is final. In a normal programming day I thought I could redefine the entire instance by redefining the this reference inside the own class:
public void method() {
this = new MyObject("arg1", arg2, arg3); //it throws a compile error
}
Why the this reference is final in Java?
The problem is not that this is a final reference - it's not itself a reference at all. this is a keyword that "denotes a value that is a reference to the object for which the instance method or default method was invoked" (JLS ยง15.8.3).
Furthermore, it wouldn't make sense to reassign it in the sense that a variable can be reassigned. Remember that reassigning a reference changes only that reference, and not other references that might point to the same object. So reassigning this would not only be insane but also useless.
I find this question interesting from a theoretical point of view.
From a technical point of view this cannot work, as in Java we have pass-refererence-by-value ( http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html ) and cannot swap out objects where some other parts of code hold a reference to that object -- i.e. a true swap method is not possible in Java (see the linked article).
While you could theoretically reassign this, all other references to the object would not change and make the operation pretty senseless.
The closest thing you can achieve is a copy constructor.
this is not a variable you can assign a value to. It is a built-in expression returning the object that is the context for the method currently executing.
While re-assigning this might be useful for some nice hacks, it would mess up all kind of things.
The this keyword is used to provide a reference to the current object within its class. Mostly, it is used to clarify scope issues with local variables which have the same identifier as a class member. E.g.
public void function (int param) {
this.param = param
}
Reassigning it to another object goes beyond the task assigned to the keyboard. What you want to do, (reassing a reference) can be achieved on the upper context, i.e. the context in which the object was created (and a reference to it was assigned).
Wrong thinking about this. this is just a keyword(not variable) in java which referenced to current instance and its a compilation restriction that keyword(any not only this) can not be initialized.
I'm working with reflection read and writing objects. I have the problem that I am reading in primitive types; but want to tell the read method to read them as their wrapper (so read a char as a Char). It seems as if there should be a simple static method I can call which would take the primitive Class and return it's wrapper's Class. so for example I could provide char.class and get the Char object's class returned.
I know it's easy enough to hard code this, but that looks ugly; and it seems like this would come up common enough to be worth Sun including a static helper method. I've looked and can't seem to find it, but I still find it hard to believe the method doesn't exist. Can anyone point me to the name of the method?
Thanks.
There appears to be nothing in the JDK, but there's the Primitives class in Guava, which allows you to write:
Primitives.wrap(char.class)
to get Character.class.
In the JDK's tools.jar there's is typeUtils.boxedClass(primitive.type) which deals with Symbol objects. I know it's not what you want, but I'll throw it in for reference and in case what you look for is actually around it.
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.