When creating a reference variable, what are we exactly doing? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Noob here, with some questions about fundamental things in Java.
If we have a class Person with a constructor (also Person) we can create a reference variable like this:
Person johnny = new Person();
Let's say we have just created in a class People an object, johnny.
It holds an "address" to where the object and its values are kept, unlike objects of primitives types do (e.g. int x = 5; has the value 5, johnny is a "link" to the value - if I've understood things correctly.)
1st word: Person is a class/type (<-- edited here), but:
What does a class/type do? What does it entail? Perhaps: what does a type do, if it is not a 'primitive type'?
2nd word: johnny is a reference variable, of type Person.
- If I am missing something, please enlighten me :)
3rd word: new this just states that we are creating the new object.
4th word: second Person:
This is the object we are creating?
Is this the constructor or the class we are referring to?
ALSO:
The value (address) that the variable is referring to is everything after the equal sign? Is the address new Person?
LASTLY: Polymorphism.
So if we have a sub-class Adult, which extends the super-class Person, then we can do this:
Person amanda = new Adult();
What are we doing now?
Is amanda of class type Person and refers to an object in the class Adult?
Thanks for your help :)

1st word: 'Person' is a class type
Yes, but it might just as well be a primitive type, does not matter for that "first word" which is the type declaration for the variable.
Another example would be
int a = 1;
When you declare a variable or parameter in Java, the name is preceded by the type.
2nd word: 'johnny' is a reference variable, of type Person
That's right. You name your variable johnny here. And its type is what you specified for it right in front of the name.
3rd word: 'new' this just states that we are creating the new object.
new means that we are calling a constructor (of the class that is following the new). That is indeed how you create objects in Java.
4th word: second 'Person
That is the name of the class that you are calling the constructor of. This will always return a new instance of exactly that class (not of a subclass). There can be more than one constructor to choose from for a given class, they are differentiated by parameter counts and types (in your case, a constructor without any parameters).
The value (address) that the variable is referring to is everything after the equal sign? The address is 'new Person'?
new Person() returns a reference to the newly created object instance. It will be stored in your variable johnny.
LASTLY: Polymorphism.
Your Adult class is a subclass of Person. This means that you can use it in all situations where a Person would be required. In particular, you can assign it to a Person-type variable (such as johnny) and call all Person methods on it.

This is all too confused for words.
When creating a reference type, what are we exactly doing?
Nothing. There is no such operation in Java.
When we have a class (or super-class, I'll get back to that) Person with a constructor (also Person) we can create a reference type like this:
No you can't. What you are creating here is a reference. You are not creating a type, let alone a 'reference type'.
Person johnny = new Person();
We have just created in a new class People (e.g.) an object, johnny.
I see no evidence of a class People, but I'll take your word for it.
It holds an "address" to where the object and its values are kept, unlike objects of primitives types do (e.g. int x = 5; has the value 5, johnny is a "link" to the value - if I've understood things correctly.)
Correct.
1st word: 'Person' is a class type, but:
No it isn't. Person is a class. Period.
What does a class type do? What does it entail?
Nothing because it doesn't exist. A class on the other hand is a kind of template for constructing objects from, that determines its data members and what code can be called on it.
Perhaps: what does a type do, if it is not a 'primitive type'?
It extends the type system beyond the primitive types, in a way which can be reasoned about and computed, via inheritance, interface implementation, and the Liskov substituion principle (q.v.).
2nd word: 'johnny' is a reference variable, of type Person. - If I am missing something, please enlighten me :)
Correct.
3rd word: 'new' this just states that we are creating the new object.
Correct.
4th word: second Person: This is the object we are creating?
This is the class (or 'type' if you insist) of the object we are creating.
Is this the constructor or the class we are referring to?
Both. The arguments or lack of them determine which constructor is called. The name of the constructor is the same as the name of the class, by the rules of Java.
The value (address) that the variable is referring to is everything after the equal sign? The address is 'new Person'?
The variable refers to the object that was created. There is no concept of 'address' in Java.
LASTLY: Polymorphism. So if we have a sub-classes 'Adult', which extends the super-class 'Person', then we can do this:
Person amanda = new Adult();
What are we doing now?
You are creating an object of type Adult and referring to it via a reference of type Person, which can only succeed if Person is a base class of or an interface implemented by Adult.
Is 'amanda' of class type Person
'amanda' is a reference of type/class Person.
and an object in the class 'Adult'?
amanda isn't an object at all. The object it refers to is an object of class Adult.

Related

Creating a new null object what will the instance variables be?

Let's say I have a class named Class and I created a new null object:
Class object = null
The constructor in Class is:
private int a;
private String b;
public Class() {
a = 144;
b = "Test";
c = null;
}
Will a, b, and c be equal to null?
If not, is there a way for me to create the object so that all three instance variables are null?
No. They won't be equal to anything because they won't exist. Nothing ever created an instance of Class so there is no instance.
As an analogy you're basically asking, "If I don't build a house, will that house's windows be open or closed?" They will be neither.
When you do this:
Class object = null;
What you have is a variable which can (at a later time) refer to any instance of type Class, but which currently refers to no instance.
is there a way for me to create the object so that all three instance variables are null
Kind of. You can add a constructor which doesn't set those values:
public Class () { }
And you can create an instance of that class via that constructor:
Class object = new Class();
Then you can observe your instance in the debugger to see what those values are. I'm not 100% sure in Java, but it's possible that an int can't be null. Which would make that part of the question kind of moot. (I know it can't in C#, but if it can in Java then ignore this part and carry on.)
An unassigned int local variable would be a compiler error if you try to use it. But this is a class field, not a local variable. In this case it's going to be automatically given its default value, which is generally null for reference types but 0 for primitive numeric types.
Let's say I have a class named Class
Given that java.lang.Class already exists, let's not. Let's say you have a class named MyClass.
and I created a new null object:
That's an oxymoron.
null is a reference. It's not an object. It is, in fact, the reference that means 'I refer to no object', and is the only reference that means 'I point at nothing'.
When you write:
MyClass x = new MyClass();
Then x is a treasure map, and new MyClass() is 'create a new treasure chest and bury it in the sand'. The = in the middle says: Update the treasure map named x, so that following it would lead you to the treasure I just made (new X() means: Make new treasure and bury it).
MyClass x = null;
means you have a treasure map named x which is currently blank.
If not, is there a way for me to create the object so that all three instance variables are null?
That would imply a treasure chest of the MyClass treasure type, which has room for some scratches (int a - a number), and which contains a treasure map (the String b variable). If you want to set them all to null, well, you can't - a is a primitive (int) and those aren't treasure maps, they are the actual number. You can't not have one - a cannot be null. At best, a can be 0. b CAN be null. That means there's real treasure, but the treasure contains yet another treasure map (in java it's mostly treasure maps all the way), but that one is blank. That's different from there being no treasure at all.
More generally, the question: "Can I make a new instance of MyClass such that all fields are some value I desire" is the wrong question to ask, perhaps: The general principle is encapsulation: MyClass is an API: It's like the receptionist at a big corp's office. The receptionist decides what services are available. Even if the CEO is available, if the receptionist elects not to answer the question 'can I see the CEO right now please?', then you can't see her.
Your question boils down to: "If I storm into this office and I demand to speak to the CEO, will I be allowed to?" - the only viable answer is: Well, the receptionist would decide, so you'd have to ask him. For classes: Whatever the API lets you do, you can do. But that's all you can do.
If there is no constructor that initializes these fields to null, then, no, you can't.

How does class object relation work?

What happens when we create an instance of a class? I mean, will every field and method of that class be inside that object (with allocated memory) or will it not have anything inside and have a reference to its class, instead. (First option looks like a waste of memory.)
Whenever a new object is created, new memory is allocated in the heap space (dynamic memory). This space is reserved for everything that's specific to this single instance of a class. That means every field (instance field, not the static one) would have its own separate location in memory.
For methods, things are different since they are common for all instances of a class, which means you would have one method in memory which would be referred to by each instance of a class.
If you wonder where are local variables of a method stored: they are stored on the stack, meaning they are not shared between invocations of that method.
Also, methods are stored in the 'code memory', separate from instance fields.
The full concept of OOP (Object Oriented Programming) is being able to abstract the reality by "describing" the objects.
To accomplish this purpose we're able to declare an object attributes, for example.
You can have an object Person, this person has different attributes, such as name, age, address. Also you can describe the different actions of this person, such as eating, taking a bath, etc. The abstraction of this would look like:
class Person(){
int age;
String name;
String address;
void eating(){
//describe the process of eating
}
void takeBath(){
//describe the process of taking a bath
}
}
The whole purpose of this is that afterwards you can instantiate an Object Person and it will have all of it's attributes.
You can call the object in another class and instantiate it, this call will look like:
Person person1 = new Person(); //here you are saying that you have a new variable of type person
person1.name = "Eduardo"; //You're saying that his name is Eduardo
person1.age= 28; //he is 28 years old
person1.eating(); //he's eating, I like to eat tho.
Person person2 = new Person(); //You are saying that there's another person
person2.name = "Maria"; //her name is Maria
person2.age = 31; //She's 31 years old
person2.takeBath(); She's taking a bath
As you can see I didn't have to declare again the methods or attributes of the class, simply created a new object and started setting the attributes (please be aware of the difference between declaring and setting, to declare is to say there is an attribute of X type; setting is giving a value to that attribute).
There's another very useful property in OOP called heritage. Lets say we want to describe a Programmer; a programmer is a Person and he can do whatever a person does but also he codes and has a preferred language this would look like:
class Programmer extends Person { // I'm declaring the class but also I'm saying it's a person, so it will have all the attributes and methods of the Person class.
String preferredLanguage; //I will only declare the new attribute that is preferred Language, name, age and address are set because it's a person
void code(){
//the process of making very awesome things
}
}
And then I can instantiate another object Programmer
Programmer person3 = new Programmer(); //I called it person3 so you can understand it's only a variable, you can call it as you wish.
person3.name = "Berkay"; //Set the name without the need of declaring it in the method programmer, it's been inherit by the class Person
person3.code();//it can code!
person3.takeBath(); //A method of Person
person3.code(); //method of Programmer
At this stage I'd like to point that Programmer having the attributes of Person doesn't mean the same way around. For example, trying to make this would be a mistake:
person1.code(); //person1 is a Person and it doesn't have the code method.
PS: There are a lot of things to improve in these code, it's far from using best practices. All I intend to do is to give a clear example of the way OOP works. I didn't test the code, it's only illustrative, it may contain typos

What do you call this object in Java and why do you use?

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.

Difference between an Instance and Object in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In Java, what is the difference between instance of a class and Object of a class.
For a class A, Take a look :
line 1 : A a; // Declaring a reference variable of class A
Line 2 : a = new A();// Instantiating an object of class A
So....can the line 2 also be : // Instantiating an instance of class A
which mean Instance and Object are absolutely the same thing ?
Please give an objective answer than subjective.
Line 1 declares a variable, it doesn't reference anything, though, its value is null.
Line 2 creates a new object and assigns it to the variable a.
An object is an instance of a class. A class is something used to create objects, an object is something created (instantiated) using that class as a template.
"instance" means a specific occurrence of something. For instance, you could talk about database instances, where each instance is an installation in a specific place on a specific server somewhere. Likewise with objects, an instance is a specific member of a category.
The term "instance of" is used to show you from which classes the specific object origins from. The objects Buddy, Lucky and Sparky are instances of dogs but also instances of animals. So the object itself can be an instance of multiple classes. A cat is also an instance of animals and an instance of cats but not an instance of dogs.
public abstract class Animals{...}
public class Dogs extends Animals{...}
public class Cats extends Animals{...}
The object and the instance are of different stories. It's like asking what is the difference between a Car and an Engine.
Anyway, an object is a representation of a class. A class is the file that you write and save.
Once you use a class and put it into memory, an object is created.
Instantiating is the process of using a class to create an object based on that class and putting it into memory.
A a; // Declaring a reference variable of class A
This means you are reserving a variable for a particular object or particular class.
a = new A();// Instantiating an object of class A
This means that you are using the A.class as your base class to create the object a. And this process is basically Instantiation.
Line 1, you declare an variable which type is A, but the variable doesn't have any value, its value is null.
In Line2, you created an object of Class A using new, and assign a reference of that object to variable a, in another words, you assigned a reference of A class's object to the variable a.
a is called the instance of class A, the object it refers to is called the object of A

Compile and run-time classes

Lets imagine I have a class called Person which is a generalization of another class Man. If I am to make a couple of instances of this class
Man man = new Man();
Person person = new Man();
Now, the compile-time class of the instance being referenced from the variable man is Man and the compile-time class of person is Person while the run-time class of both instances is Man. So far, im completely on board with the terminology because the instances which are created at run-time both are of class Man. But, if I where to cast the man instance as follows
Person personMan = (Person) man;
how come the run-time type of personMan is still Man? Is the run-time class of a instance only set when a new instance is created? Also, is there a way of actually getting the compile time class of a variable at runtime, so I could query what type of class personMan is (getClass would return Man).
Edit: "compile-time class of a class" was a mistake (and doesn't make much sense). What I meant was variable (hence they question about what type of class personMan is :))
It's important to distinguish between three different concepts here:
Variables (man, person)
References (the values of the variables)
Objects (the blobs of memory that the references, um, refer to)
The type of an object never changes after it's created. Casting a reference to a different type only affects the compile-time type of that expression. The result of a reference-type cast expression is always the same the original reference - it still refers to the same object, which still has the same type. (That's leaving boxing aside - and of course the cast can fail at execution time, leading to an exception.)
Also, is there a way of actually getting the compile time class of a class at runtime
If you mean the compile-time type of a variable - not if it's a local variable, without really deep inspection of the byte code. If it's a field you can use reflection to get at it. Why do you want to know?
The runtime type is the type of the new. new Man() is always Man, no matter the type of the variable where you store it.
The compile type is the type of the declared variable.
In your example
Person personMan = (Person) man;
you only can code with methods and attributes of personMan. You can also do
((Man)personMan).someManMethod();
but this can lead to a error if personMap hasnĀ“t stored a instance of Man.
In Java, variables (other than primitives) are just references to objects. The objects themselves live off somewhere else and can never be directly accessed.
In every case, you have a Man object sitting somewhere, and the different references just give access to different subsets of the capabilities of that Man object.

Categories