As part of my AP class I am learning objects, instances, references etc... So from what I understand a reference is a variable that points to something: a value, class etc . . . Therefore is it legal to say that a object is a reference to a class?
Note: I know this is subjective but I cant seem to find such a comparison anywhere else.
By the usual definition of reference you can not say that. Correct would be "An object is an instance of a class.".
The usual definition of a reference is a value which points to a memory location that is usually occupied by some object. The difference between pointers and references is that you can do pointer arithmetics on the former but not on the latter.
For example in the following code snippet:
SomeClass o = new SomeClass();
SomeClass foo = o;
SomeClass is the class and o is a reference to the instance of SomeClass returned by this particular invocation of the new keyword. new SomeClass() allocates memory for a new instance of SomeClass and calls its constructor to initialize it. foo is another reference to the very same instance of SomeClass also referred to by o. In other words, o and foo point to the same object but are not the same reference.
Object is not a reference of class, but instance of class.
No, that would not be a valid statement. An object is an instance of a class, not a reference to one. When you have something like:
MyClass var = new MyClass();
Then var is a reference to the MyClass instance to which it was assigned (new MyClass()). This instance is in turn an object.
From JLS ยง4.3.1:
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
As somebody else said, a class is a like a blueprint. When you create an object based off of the class, the computer "builds" an object by allocating memory to create "parts" (variables) based off of your class.
Therefore, the object is not a reference to the class, implying that the object simply redirects you to the class.
The object is a instance of the class.
No. That would be like saying that the scrambeled eggs you ate this morning are a reference to the abstract concept of scrambeled eggs.
Remember that a class is a blueprint, but it's not an actual, concrete object on its own. That only happens when you instantiate an object via the new keyword.
An object is really an instance of a class. Let's say we have the String class. An object of the type String is an instance of the String class, not that class itself. Given String s="foo", s's value would be a reference to an instance of the String class.
Now, every class has a java.lang.Class object that is associated with it, so String.class is a reference to an instance of java.lang.Class.
From JLS:
An object is a class instance or an array.
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
Object foo = new Object();
foo is an reference to a specific, concrete instance of the class Object but not to the class itself.
Class bar = Object.class;
bar is a reference to the Object class.
Related
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 10 months ago.
What happens when I initialize one object to another in java? Is the reference of that object copied in new object or is a new object created with same member values as in the orginal object;
A obj1=new A("apple");
A obj2=obj1;
What is the correct interpretation for this scenario?
when I initialize one object to another in java
I do not know what you mean by "to another". But you initialized only a single object.
First line
Regarding your first line:
A obj1=new A("apple");
A obj1 declares a reference variable, giving it a name obj1, and specifies that this var will hold a reference to any object of type A. This reference variable is initially null.
Calling new A("apple") constructs an object some place in memory. The result, the return value, of this code is a reference to the new object.
The = assigns that reference to be the content of the variable named obj1.
You can think of a reference variable as containing the address in memory where the beginning of that object's block of allocated memory resides. In Java we never see the literal contents of a reference variable. But we know we can reach the object via that reference variable.
In our daily work of programming in Java, we may generally think of obj1 as being the object. But actually obj1 is a way to find the object, a tether attached to the object, a line we can follow to access the object somewhere else in memory.
Second line
Regarding your second line:
A obj2=obj1;
First you declare a new variable named obj2 to hold a reference to an object of type A. Then you copied the reference from obj1 and put that copy into obj2.
You are left with:
A single object.
Two references to that single object.
It is just the reference coppied, not an actual new object in some other memory space.
Normally for deep-copy you can declare yourself a clone method in that class that uses the properties of the passed object and creates another object with new keyword and returns it. This way you will have a new object when you use clone method. More specifically you can declare your class to implement Cloneable interface and then provide an override implementation for the method clone() which already exists in parent Object class.
For shallow-copy you should again create a clone method in your class and in this method you can just use return super.clone() so that the default clone() method provided by Object class will be used to make a shallow-copy of the object meaning only primitive fields will be actually copied and for any non primitive fields the reference will be copied instead.
For your simple example where the field in this class is only some String you can use the shallow copy of clone already provided by Object class and this will seem enough.
If however you had more non primitive fields in this class, then you will had to override your clone method and provide some implementation so that a deep copy could be returned.
I understand how the object returned by the method contains getClass() metadata of the object it is called on, but is the class object being returned an instance of the class of the object it is called upon? This method can be called on any object in Java, so any instance or array. Does it differ for instances and arrays since arrays are in a way special objects?
let's assume a class Dog. if you write new Dog().getClass() or just Dog.class you'll get an instance of Class<Dog>. More in the official docs: https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
I don't really understand how the class keywords work in some instances.
For example, the get(ClientResponse.class) method takes the ClientResponse.class. How does it use this when it gets it, and what are the advantages over just passing an instance of it?
SomeClass.class
returns a Java Class object. Class is genericized, so the actual type of SomeClass.class will be Class<SomeType> .
There are lots of uses for this object, and you can read the Javadoc for it here: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html
In ClientResponse.class, class is not a keyword, neither a static field in the class ClientResponse.
The keyword is the one that we use to define a class in Java. e.g.
public class MyClass { } /* class used here is one of the keywords in Java */
The class in ClientResponse.class is a short-cut to the instance of Class<T> that represents the class ClientResponse.
There is another way to get to that instance for which you need an instance of ClientResponse. e.g
ClientResponse obj = new ClientResponse();
Class clazz = obj.getClass();
what are the advantage over just passing a instance of it?
In the above example you can see what would happen in case obj was null (an NPE). Then there would be no way for the method to get the reference to the Class instance for ClientResponse.
The Class class, which is different from the class keyword, is meta-data describing instances. It tells you about the methods, data members, constructors, and other features of the instances that you create by calling new.
For example get(ClientResponse.class) method takes the
ClientResponse.class how does it uses this when it gets it and what
are the advantage over just passing a instance of it?
You can't pass an instance of ClientResponse to this method; it's expecting meta-data about all instances of ClientResponse. If you passed an instance, you'd expect that the method might change the state of that instance. But passing the meta-data about all instances might allow the method to create a new kind of instance (e.g. a dynamic proxy) or do something else that depends on the meta-data about all instances of ClientResponse. See the difference?
A class is a "blueprint" of the object. The instance is a object.
If we have
public class SomeClass {
int a;
SomeClass(int a) {
this.a = a
}
}
We can have an instance of this class
SomeClass c = new SomeClass(10);
c is an instance of the class. It has a integer a with value 10.
The object SomeClass.class represents a Class.
Here SomeClass.class is a object of the type Class which has the information that SomeClass is
a concrete class with
one constructor
with a integer member variable
and lots more other metadata about the class SomeClass. Note that it does not have a value for a.
You should use get(c) incase you are planning to do something with a instance of c like call c.a or other useful functions to manupulate/get data of the instance.
You should use get(SomeClass.class) when the get returns something based on the fact that the argument is some type of class. For example, if this is a method on a Registry class which has a map which retrieves a implementation class based on type of class passed in.
The very most important fact is - you don't need to have an instance to call the method. It's critically useful in situations when you cannot for some reason instantiate a class, e.g. it's abstract, or have only private constructor, or can only be correctly instantiated by some framework, like Spring or JSF.
You can then call get to obtain an object of a requested type without even knowing where it does come from and how it get's created.
Here ClientResponse.class is an instance of Class<ClientResponse>. In general Class object represents type of an object. When you create new instance:
Object obj = new ClientResponse()
you can retrieve the class (type) of that object by calling:
obj.getClass()
So, why would you pass Class objects around? It's less common, but one reason is to allow some method create arbitrary number of instances of a given class:
ClientResponse resp = ClientResponse.newInstance();
There's a lot of ways Class objects can be used. This is used for Reflection. Below is a link that can help you understand more.
http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code. Since this field is public and static, we can access it using dotted notation along with class name as in your case it is ClientResponse.class.
I'm preparing for a java exam. I came across the following question
String s = new String ("hello");
Object o = (object) s;
Since o and s are both references that point to the same object, is there any difference in accessing the object through the reference s over the reference o?
Would I be right in saying that all objects (like the one being reference by s) are subclasses of Object in Java and as such using the reference s you will be able to call the methods known by the superclass Object like clone() and the methods known by String like length(). Whereas, the superclass object reference o will only be able to call it's own methods and not those of the subclass? Thanks.
The difference is that by using o you will not be able to call string specific methods unless you cast it back to String.
However, any method that you call on o that is defined on the String class will call the later version of the method. For example, o.toString() will return "hello", and not the descriptor that the Object.toString() normally returns. This is called polymorphism.
In Java, if I declare,
MyClass obj;
Is obj called a "reference" or an "object". I am not instantiating class here.
obj is a Reference to an instance of MyClass.
Currently, that Reference is NULL because you haven't assigned it to refer to any instance.
Technically MyClass must be a subclass of Object, so it is possible to say that obj is a Reference to an instance of Object as well.
Reference: A variable that points to some object in memory.
It is stored in stack they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also.
Object: An instance of class that is created dynamically.
It is stored in heap
Example:
MyClassI aObj,aObj1;
aObj=new MyClass2();
At first line aObj and aObj1 are references
At second line aObj referencing to object of MyClass2(New operator creates an object of Myclass2 and its address is assigned to aObj).
To understand even better consider a class Car which has driverName as a member.
Car c1,c2;
c1.driverName="Andrew"
c2.driverName="Gabriel"
System.out.println(c1.driverName);//gives Andrew
System.out.println(c2.driverName);//gives Gabriel
c1=c2;
c2=null;
// gives gabriel because the address of c2 is copied to reference c1.
// the object is not nullified because c2 is just a reference when
// assigning null the address that is stored on c2 in nullified not
// the object it points..
system.out.println(c1.driverName);
In computer science, a reference is a
value that enables a program to
indirectly access a particular data
item, such as a variable or a record,
in the computer's memory or in some
other storage device. The reference is
said to refer to the data item, and
accessing that data is called
dereferencing the reference.
In computer science, an object is any
entity that can be manipulated by the
commands of a programming language,
such as a value, variable, function,
or data structure. (With the later
introduction of object-oriented
programming the same word, "object",
refers to a particular instance of a
class)
so obj is a reference and new MyClass() can be seen as an object
obj is a Reference of type MyClass. The current reference does not point to anything (ie: null).
Sometimes you'll hear people say "Design an method that takes an object as a parameter and..."
If you're new to programming, and especially with Java, such statements can lead to some confusion. These people are using the word "object" to refer to an instance of a class in very general OOP terms, not necessarily Java specific.
When we're talking specifics about Java and the code you have there, it is a reference to an instance of MyClass, which is NULL.
'obj' is a variable. It holds either a reference or null. If it holds a reference, that refers to an object.
In Java, all objects are accessed by reference, and you never have direct access to the object itself.
reference :- is a variable that has a name and can be used to access the contents of an object, A reference can be assigned to another reference passed to a method, or returned from a method. All references are the same size, no matter what their type is Like "Object object ;".
object:- is an entity that's exists in memory allocated by the Java run time environment, An object sits on the heap and does not have a name Like "Object object=new Object();".
so MyClass obj Here is A reference referred to Null.
We can summarize this principle with the following two rules:
The type of the object determines which properties exist within the object in memory.
The type of the reference to the object determines which methods and variables are accessible to the Java program.
The reference is a variable that has a name and can be used to access the contents of an object. A reference can be assigned to another reference, passed to a method, or returned from a method.
All references are the same size, no matter what their type is.
An object sits on the heap and does not have a name. Therefore, you have no way to access an object except through a reference. Objects come in all different shapes and sizes and consume varying amounts of memory. An object cannot be assigned to another object, nor can an object be passed to a method or returned from a method. It is the object that gets garbage collected, not its reference.