I have 2 classes, A and B. A contains properties that I want to use in B.
I want to put all objects I initialize in B into an array every time a new object is initialized. With this code, the first object should go to array-position 1, the second object to array-position 2 and so on. The variable n basically determines to which position the object should go.
I know that with "this." I can access individual variables from this object (as you can see with x and y), but I don't know how I can access the object as a whole. You see that I have a comment in my code, which shows what I try to do. It doesn't work, because it's not the proper syntax.
What do I have to put there so it will work?
class A{
private int x, y;
private static int n;
A(int x, int y){
this.x = x;
this.y = y;
n++;
//B.object[n] = this.object;
//I tried this but it doesn't work
};
}
class B{
public static A[] object = new A[10];
public static void main(){
A object1 = new A(1,2);
A object2 = new A(3,4);
A object3 = new A(5,6);
};
}
Your object reference inside B class holds an array of A types, so you need to simply set B.object[n] = this; as shown below (Here, this itself represents the current A object, so no need to say this.object):
class A{
private int x, y;
private static int n;
A(int x, int y){
this.x = x;
this.y = y;
n++;
B.object[n] = this;
};
}
class B{
public static A[] object = new A[10];
public static void main(String[] args){
A object1 = new A(1,2);
A object2 = new A(3,4);
A object3 = new A(5,6);
};
}
Also, in Java, main method takes String[] as input arguments (shown above) which will be the method executed by the JVM at the start (though with main(), the code compiles, but JVM does not invoke it at the start).
But as a side note, remember that what you are trying do creates circular dependencies (class A depends on class B and then class B depends on class A), so avoid that.
Although javaguy's solution solves your problem, it will probably cause the compiler to give a warning about a "leaking this" in the constructor.
This could be potentially dangerous in a multithreaded environment because it allows you to get hold of a reference to A (via B.object) before A has fully run through its constructor.
A better pattern in this case would probably be to have a static helper method in A that constructs those objects for you, adds them to the list and then returns a reference to them.
class A{
private static int n;
private int x, y;
public static A createA(int x, int y){
A result = new A(x, y);
n++;
B.object[n] = result;
return result;
}
private A(int x, int y){
this.x = x;
this.y = y;
}
}
class B{
public static A[] object = new A[10];
public static void main(String[] args){
A object1 = createA(1,2);
A object2 = createA(3,4);
A object3 = createA(5,6);
}
}
By making the constructor of A private, you ensure that new A(1,2) won't work from another class, so you have to use the helper method to get an instance.
Related
Here when I run this below code I get called as the output and I was wondering why not called new. Since 1 comes under both short and int range.
public class MyClass {
private int x;
public MyClass(){
this(1);
}
public MyClass(int x){
System.out.println("called");
this.x = x;
}
public MyClass(short y){
System.out.println("called new");
this.x = y;
}
public static void main(String args[]) {
MyClass m = new MyClass();
System.out.println("hello");
}
}
1 is an int literal, so MyClass(int x) is chosen.
Even if you remove the MyClass(int x) constructor, MyClass(short y) won't be chosen. You'll get a compilation error instead, since 1 is not short.
You'll have to cast 1 to short - this((short)1); - in order for the MyClass(short y) to be chosen.
As an addition to others answer I can suggest you to check which constructors are being called when you initialize variables of other types using the same literal:
short s = 1;
int i = 1;
And then check which constructor of MyClass is being called as you call them with above arguments.
I am trying to assign value to a class variable via a method. However, after the execution comes out of the scope of the method, the variable is still initialized to the default value. How do we accomplish this in Java?
I want to initialize x to 5 by calling the method hello(). I don't want to initialize by using a constructor, or using this. Is it possible?
public class Test {
int x;
public void hello(){
hello(5,x);
}
private void hello(int i, int x2) {
x2 = i;
}
public static void main(String args[]){
Test test = new Test();
test.hello();
System.out.println(test.x);
}
}
When you do
hello(5,x);
and then
private void hello(int i, int x2) {
x2 = i;
}
it seems like you might be trying to pass the field itself as parameter to the hello method, and when doing x2 = i you meant x2 to refer to the field. This is not possible, since Java only supports pass-by-value. I.e. whenever you give a variable as argument to a method, the value it contains will be passed, not the variable itself.
(Thanks #Tom for pointing out this interpretation of the question in the comments.)
The class property x is only visible by using this.x in hello() because you have declared another variable called x in the method's arguments.
Either remove that argument:
private void hello(int i) {
x = 5;
}
Rename the argument:
private void hello(int i, int y) {
x = 5;
}
Or use this.x to set the class property:
private void hello(int i, int x) {
this.x = 5;
}
You can create two methods.
public void setX(int a)//sets the value of x
{
x=a;
}
public int getX()//return the value of x
{
return x;
}
call setX to set the value of x and getx to return the value x.
Essentially these are called getter and setter and we use them to access private members from outside the class.
I would like to create the method .add(int,int) for and ArraYList of the following data structure:
class CPoint {
int x;
int y;
}
in order to use it in the following way:
ArrayList<CPoint> ar = new ArrayList<CPoint>();
ar.add(100,100);
I know I have to start with something like this:
class CArrayListPoints extends ArrayList<CPoint>{
}
but not sure how. Please help me in this matter.
EDIT: implement <-- extends
You can create a class like this:
class CArrayListPoints extends ArrayList<CPoint>{
public void add(int x, int y){
super.add(new CPoint(x, y);
}
}
Use this way:
CArrayListPoints list = new CArrayListPoint();
list.add(10, 10);
Probably You are looking something like this
class CPoint {
int x;
int y;
}
class CArrayListPoints extends ArrayList<CPoint>{
public void add(int x, int y){
CPoint p = new CPoint();
p.x = x;
p.y = y;
add(p);
}
}
If you want a list with two values HashMap http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html is what you need. If you insist on using Arraylist, just make a add(int a,int b)method and have each CPoint have a field that contains the x value.
I have a problem
I have some classes of objects, they are called "cat" "dog" etc..
Within these classes I have assigned each cat and dog object their own integer energy level (so when they "move" through a 2dimensional array they loose and gain energy).
I reference it by saying this.energylevel.
Because "energylevel" it is specific to each object I cannot make it static.
how can I let the "dog class" see the energy level of the cat objects that is stored non statically within the "cat class"?
and I cannot instantiate Cat c = new Cat(); within the dog class it is already done within the main method.
This is all part of a massive project so forgive me if I have not explained it clearly enough
You can add a static method inside the Cat object that will return the non-static variable based on the Cat's ID. You'll need to keep a list of Cats in a static map inside the Cat object.
private static HashMap<String,Cat> cats = new HashMap<String,Cat>();
...
public static int getEnergy(String catId) {
Cat myCat = cats.get(catId);
return myCat.getEnergy();
}
public int getEnergy() {
return this.energy()
}
Alternatively as requested, if you want to search by X,Y:
private static ArrayList<Cat> cats = new ArrayList<Cat>();
private int energy = 100;
private int x = 0;
private int y = 0;
...
public static int getEnergy(int x, int y) {
//Energy of -1 being the error (not found) state.
int energy = -1;
for(Cat cat : cats) {
if(cat.getX() == x && cat.getY() == y) {
energy = cat.getEnergy();
}
}
return energy;
}
public int getEnergy() {
return this.energy()
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
Can we swap two numbers in Java using pass by reference or call by reference?
Recently when I came across swapping two numbers in Java I wrote
class Swap{
int a,b;
void getNos(){
System.out.println("input nos");
a = scan.nextInt();
b = scan.nextInt(); // where scan is object of scanner class
}
void swap(){
int temp;
temp = this.a;
this.a = thisb;
this.b = this.a;
}
}
In the main method I call the above mentioned methods and take two integers a,b and then using the second method I swap the two numbers, but relative to the object itself....
Does this program or logic come under pass by reference?
And is this correct solution?
Yes and no. Java never passes by reference, and your way is one workaround. But yet you create a class just to swap two integers. Instead, you can create an int wrapper and use pass it, this way the integer may be separated when not needed:
public class IntWrapper {
public int value;
}
// Somewhere else
public void swap(IntWrapper a, IntWrapper b) {
int temp = a.value;
a.value = b.value;
b.value = temp;
}
As the comments show, I might not have been clear enough, so let me elaborate a little bit.
What does passing by reference mean? It means that when you pass an argument to the method, you can change the original argument itself inside this method.
For example, if Java was pass-by-reference, the following code will print out x = 1:
public class Example {
private static void bar(int y) {
y = 10;
}
public static void main(String[] args) {
int x = 1;
bar(x);
System.out.println("x = " + x);
}
}
But as we know, it prints 0, since the argument passed to the bar method is a copy of the original x, and any assignment to it will not affect x.
The same goes with the following C program:
static void bar(int y) {
y = 1;
}
int main(int argc, char * argc[]) {
int x = 0;
bar(x);
printf("x = %d\n", x);
}
If we want to change the value of x, we will have to pass its reference (address), as in the following example, but even in this case, we will not pass the actual reference, but a copy of the reference, and by dereferencing it we will be able to modify the actual value of x. Yet, direct assignment to the reference will no change the reference itself, as it is passed by value:
static void bar(int &y) {
*y = 1;
y = NULL;
}
int main(int argc, char * argc[]) {
int x = 0;
int * px = &x;
bar(px);
printf("x = %d\n", x); // now it will print 1
printf("px = %p\n", px); // this will still print the original address of x, not 0
}
So passing the address of the variable instead of the variable itself solves the problem in C. But in Java, since we don't have addresses, we need to wrap the variable when we want to assign to it. In case of only modifying the object, we don't have that problem, but again, if we want to assign to it, we have to wrap it, as in the first example. This apply not only for primitive, but also for objects, including those wrapper objects I've just mentioned. I will show it in one (longer) example:
public class Wrapper {
int value;
private static changeValue(Wrapper w) {
w.value = 1;
}
private static assignWrapper(Wrapper w) {
w = new Wrapper();
w.value = 2;
}
public static void main(String[] args) {
Wrapper wrapper = new Wrapper();
wrapper.value = 0;
changeValue(wrapper);
System.out.println("wrapper.value = " + wrapper.value);
// will print wrapper.value = 1
assignWrapper(w);
System.out.println("wrapper.value = " + wrapper.value);
// will still print wrapper.value = 1
}
}
Well, that's it, I hope I made it clear (and didn't make too much mistakes)
import java.util.*;
public class Main
{
int a,b;
void swap(Main ob)
{
int tmp=ob.a;
ob.a=ob.b;
ob.b=tmp;
}
void get()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a and b: ");
a=sc.nextInt();
b=sc.nextInt();
}
public static void main(String[] args) {
Main ob=new Main();
ob.get();
ob.swap(ob);
System.out.println(ob.a+" "+ob.b);
}}