I have a question which I consider to be rather vague.
How many objects(instances) of class A are created by the following method:
void create() {
A a;
A b;
A[] s;
a = new A();
b = a;
s = new A[10];
}
class A { }
I am not sure how to count the array. We can easily see that the objects a and b are the same, but do we consider the array itself to be an object, or do we consider that it has 10 objects, which are null?
I thank you in advance!
s = new A[10] is an object of A[], it's not an object of class A.
Therefore, you don't count the 10 null references of the array.
only a = new A() is created.
I ran the above code through the Eclipse profiler and found that only one instance was created a = new A() which b also references. Hence there was only one instance created. The array of type A was not allocated as null until I assigned an object to the first index of the array. Hope this helps.
Related
I have a for loop that adds values to an array of objects.
Say I have class B, and make a array of class B inside class A.
like
B array1 = new B[10];
How can I name each object with a reference name that will look like
for(int x = 0; x<array1.length; x++){
B object+x = new Bar(int value1, int value2);
x++;
}
each time it goes through the for-loop
I'm not sure how to add a number after "object" so that I can have 10 array objects like object1, object2, object3...
I want to be able to reference these saved objects inside another method in class A, without creating a new object each time, and then call a method from class B on the object.
Sorry I cant provide much code, its part of a assignment and I cant post my code.
You cannot this. In Java you cannot create variables with dynamic names calculated in runtime. If you think your teacher asked this of you, it is very likely a misunderstanding.
The closest would be probably something like:
Bar[] array1 = new Bar[10];
for(int x = 0; x<array1.length; x++){
array1[x] = new Bar(...);
}
As per the below statement,
An array of subclass may be assigned to an array of its superclass. An array of implementing class may be assigned to an array of its interface type. Size is irrelevant.
I wrote below sample code to check the behavior of size in array
interface I{}
class C implements I{}
/* dummy.java*/
public class dummy{
public static void main(String[] args){
C[] c = new C[6];
I[] i = new I[2];
c[0] = new C();
c[1] = new C();
c[2] = new C();
c[3] = new C();
c[4] = new C();
c[5] = new C();
i = c;
System.out.println(i[5].getClass());
}
}
When i say, new C[6];, an object [null,null,null,null,null,null] gets created of type class [LC and c points to this object. When i say, new I[2];, an object [null,null] gets created of type class [LI and i points to this object.
My question:
How interface array is working here, when i say i[5], despite an object [null, null] being created after defining new I[2]? What exactly is happening when i say i = c;? Is size of array of interface new I[2]; getting modified during assignment i = c;?
What that quote is trying to say is that the size of an array is part of the object, ie. it is not part of the reference or the variable type.
In
i = c;
you are assigning a copy of the value of the reference held in c to i. That is, i will reference the same instance as c.
Is size of array of interface new I[2]; getting modified during assignment i=c;?
No, that's the whole point. i and c are just variables. Variable assignment has no side effects.
When you set
i=c
You are setting i to point to the object created by c. Therefore, i will now point to C[6]; < this array
So...
i[1] = new I();
c[1] will return a I object
how to use getter setter in two different class
Class A{
int a = 10;
GetterAndSetter gs = new GetterAndSetter();
gs.setValue(a);
}
Class GetterAndSetter {
int a ;
public void setValue(int a){
this.a = a;
}
public int getValue(){
return a;
}
}
class B {
int c;
GetterAndSetter gs = new GetterAndSetter();
c = gs.getValue();
}
While printing c it gives null. And tell me if it is valid or not.
Whenever you write this
GetterAndSetter gs = new GetterAndSetter();
what you're doing is to create a new instance of GetterAndSetter. Two instances that you create won't have any connection between them.
Inside class A, you create a new instance, and set its value. Inside class C, you create a new instance, and read its value. But because you've got two different instances, the value you're reading isn't connected with the value you're setting.
This is roughly like:
I buy an envelope, and put some money inside it.
Later on, I want to get the money back, so I buy a new envelope, and look for the money inside it.
You have to be looking in the same envelope that you put the money in, if you want to find it!
In class A, your code creates a new instance of GetterAndSetter and sets a value to the property. In class B, however, your code creates again another new instance of GetterAndSetter , then gets the value.
The instances your code works with in classes A and B are not the same - hence you don't obtain the values set in A when trying to get it in B. The instance of GetterAndSetter created in B is not used anymore after the code in B exits.
To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B. You can do this e.g. by passing it as a parameter to a method of B, or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter.
An example of the first option (pass as parameter):
Class A{
...
GetterAndSetter createAndSet();
int a = 10;
GetterAndSetter gs = new GetterAndSetter();
gs.setValue(a);
return gs;
}
...
}
class B {
...
void getValueFromGetterAndSetter(GetterAndSetter gs) {
int c;
c = gs.getValue();
...
}
...
}
To connect the instances, we of course also need to have another piece of code (assuming instances of A and B exist already):
...
b.getValueFromGetterAndSetter(a.createAndSet());
...
You have used different reference. You should use same reference so that only you can access the value.
you need to understand the basics of oops, you have created one instance inside class A and you are trying to access in Class B which is possible only if you pass the reference of that object from Class A to B. In that case you have to have the instance of GetterAndSetter which you have created in Class A in Class B, instead you have created another new instance which will create new reference in memory, and the class variable a will be null.
In your code, both class A and B create new objects for GetterAndSetter. Hence they are not shared between these classes. Thats why you are getting null.
I wounder how your code print null for C. I think it would be "0" instead.
It is valid, here is what happens:
You create object gs in class A
Then you set the value of a of that object to 10
You then create another object gs in class B
Last but not least, you ask the object gs from class B what its value for a is.
Guess what, its NULL as you did not set its value anywhere so it wont return one.
This is the code I have, please look at it before you read the question
package ict201jansem2012;
public class Qn3b {
public static void main(String[] args) {
int a = 1;
int b[] = {4,5};
String s = "Good luck!";
method1(b[1]);
System.out.println("(1) b[0] = "+b[0]+"; b[1] = "+b[1]);
method2(b);
System.out.println("(2) b[0] = "+b[0]+"; b[1] = "+b[1]);
method3(a);
System.out.println("(3) a = " + a );
method4(s);
System.out.println("(4) s = " + s );
}
public static void method1(int b) {
b = 7;
}
public static void method2(int[] b) {
b[0] = 3;
}
public static void method3(int a) {
a = 3;
}
public static void method4(String s) {
s = "UniSIM";
}
}
Output:
(1) b[0] = 4; b[1] = 5
(2) b[0] = 3; b[1] = 5
(3) a = 1
(4) s = Good luck!
So my question is ,
This is intresting for me to know as learning programmer. The int b array 0 index value has changed, but not the other variables like the String s and int a. Before i ran this program I roughly thought in my mind that the variable will change their values as the methods are called ,this is because the method is being called and the main method vairable such as a,s and b array are passed and then they are being modified.
So in a nutshell why is that the b array 0 index is changed while the other variables are not changed?
Because you said you were a beginner programmer, I'll do a little writeup to explain (or try to explain) exactly what is happening.
It is because you are passing an argument to your method1 - method4 methods
These arguments, themselves, are references to other objects.
When you use the assignment operator, an equals sign, you overwrite that reference for the value in the current scope - where variables can be 'seen'.
In your code:
In the case of method1 you are creating a new reference, the variable can only be seen within that scope. That is, when you then go b = << expr >> you are assigning the variable b within method1's scope the value, not b in the main scope. The same is true of your method3 and method4 methods, you are assigning a new value to the respective variables within that scope, as you are creating new references rather than altering the original objects.
But, method2's code behaves differently, this is because you are mutating the object inside that code. You are altering the object directly - rather than creating a new reference inside that scope.
Consider the code below
int[] array = new int[] {1, 2};
public void test()
{
method1(array);
System.out.println(array[0] + ", " + array[1]);
method2(array);
System.out.println(array[0] + ", " + array[1]);
}
// because we are working with objects, the identifier, can be different to the arrays identifier
// in this case, I've chosen to use 'a' instead of 'array' to show this
public void method1(int[] a)
{
// this mutates the array object
a[0] = 2;
}
public void method2(int[] array)
{
// this overwrites the method2.array but not the global array
array = new int[] { 1, 2, 3 };
}
We create a new array, with identifer 'array' in the global scope. (In Java, this would be the classes own scope)
In method1, we take an argument, which is the same object being passed as the global array object, so when we mutate it, both objects will change. So, the first print statement will be
"2, 2"
Where array[0] has been altered
N.B. Because we dealing with objects, the 'name' of the variable doesn't matter - it will still be a reference to the same object
However, in method2, we take an argument, like in method1, but this time we use the assignment operator to assign that variable to a new value in the scope that it's currently in - so the global array isn't altered, so we still print out
"2, 2"
For a beginner programmer, I would personally write a few test programs where you get to fully understand how variables and scopes work.
But just know, everytime you create a new block of code, a new scope is created, local variables to that scope can only be seen in that scope and ones below it.
For instance:
public void test()
{
int a = 5;
method1(a);
System.out.println(a); // prints 5
}
public void method1(int a)
{
// a is only viewable in the method1 scope
// and any scopes below it, that is, any scopes created within method1
// and since we use an assignment operator, we assign method1.a a value, not global 'a' a value
a = 123;
if (true)
{
// this is a new scope, variables created in this block cannot be seen outside it
// but can see variables from above it
System.out.println(a); // prints 123
}
}
Here, we create a new scope inside method1 inside the if statement, which can see a above it. However, because method1 and test's scopes are both independent, when we use the assignment operator, we assign the value of a to the local scope. So a is different in both test and method1
I hope you understand better now.
I'm not very good at conveying things, but if it even helped a little bit in understanding scopes I did well, plus, it was fun.
Java is pass-by-value, but most values (everything that's not a primitive, in this case int[] and String) are references, which means they act like pass-by-reference.
Here's a nice writeup: http://javadude.com/articles/passbyvalue.htm
arrays are special type of objects and memory will be allocated on HEAP. When you pass array as parameter to method it will be pass as reference-value (copy of the reference).
This means initial b and this new reference points to same object. Unless new reference points to another object, changes on this reference will reflect on same object. That is why you are seeing value reflected on original array.
All of the values were passed TO the inner methods, but the inner methods returned nothing. However, method2 modified the internal value of the array that was passed to it, so that inner value appeared modified on return.
Note that method2 is the only one where you did not assign to the variable (parameter) itself, but rather assigned to an element of the object whose reference was passed in.
There is a critical difference between modifying the reference (pointer) to an object, and modifying the object itself.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I copy an object in Java?
How can I initialize an object (say A) in java and set its initial member values equal to a second object (say B). After initialization I want to modify the members of A without modifying the members of B. So at initialization of A I only want to copy the data of B. How is this done in a nice way??
You could implement and use clone
MyClass b = new MyClass();
MyClass a = b.clone();
Note: some classes are not Cloneable, or have broken implementations. e.g. only have a shallow copy when they should be a deep copy.
If the class is Serializable you can serialize it and deserialize it in memory. Not exactly nice but it works.
Or you could create your own "copy" constructor.
One possible solution for that would be implement clone method on your class and use clone as follows:
MyClass a = new MyClass();
MyClass b = a;
You will notice that clone() isn't really a public method, so your will need to expose it. Additionally you need to tell Java that your object is Cloneable (this is done making your class implement Cloneable). The following code ilustrate it:
public class MyClass implements Cloneable {
#Override
protected MyClass clone() throws CloneNotSupportedException {
return (MyClass)super.clone();
}
}
That all depends on the type of the members. I'll give an Example:
class A
{
public float value;
public int[] anArray;
public A(B b)
{
//primitive may be assigned directly.
this.value = b.value;
// other types different approaches:
//copy the contents of the array
this.anArray = new int[b.anArray.length];
System.arraycopy(b.anArray, 0, this.anArray, 0, b.anArray.length);
}
}
class B
{
float value;
int[] anArray;
public B(int size)
{
this.value = 3f;
this.anArray = new int[size];
for (int i = size - 1; i >= 0; i--)
{
this.anArray[i] = i * 10;
}
}
}
B b = new B(5);
A a = new A(b);
Cloning is a straightforward option for copying. If you ever want to do something where you need more control, create your own method that performs your copy exactly how you need it:
public MyType copy()
{
MyType a = new MyType();
// Initialize how you need to here, use the object this was called from if you'd like
a.property = this.property;
// etc.
return a;
}
This gives you more direct control, but takes more time to code. If clone will suit your purposes, stick to that.
EDIT: I am going to give an example based on your comments on this answer.
Let us assume we have the following types:
TypeA: has the following member variables
int number = 5; // Default value built in by constructor.
int letter = 'x'; // Value is 'a' when constructed but has been changed.
ArrayList<TypeB> list = {b1, b2, b3} // All are initialized.
TypeB: has the following member variables
double decimal = 5.32
TypeC someObject = ...
TypeC: has some stuff, but we are going to ignore it.
Now, When we want to copy TypeA, we must do the following:
Copy over the number and character directly as they are value types.
Copy over a reference to the ArrayList which contains a reference to some TypeBs.
Luckily those are easy steps.
int copyNumber = this.number;
char copyChar = this.letter;
ArrayList<TypeB> copyList = this.list;
return new TypeA(copyNumber, copyChar, copyList);
Now that assumes a particular constructor that takes those three arguments, but hopefully you get the idea.
It would get tricky if you wanted to just get values, not references to all of the TypeBs in the ArrayList. You would have to loop through the ArrayList and create new TypeBs that copied all of ITS values (double and TypeC objects as either references or values...)
In short, what you want is an easier copy to perform. Simple assignment operators copy values with primitive types and references with Objects.