I want to set the value of the next array object whenever an object is created in my main function.
This is the object
public class MyObject{
private int objCount = 0;
private int i = 0;
public class Property{..}
public Property propertyArray[] = new Property[12];
}
Main function creates an empty object and adds properties to the property array.
The object needs to keep different number of properties.
MyObject foo = new MyObject();
foo.add("ID", 2);
foo.add("MIE",132);
MyObject bar = new MyObject();
bar.add("REV", 22);
There is also an array of the object,
public MyObject[] ObjectArray = new MyObject[5];
I want to call a method that increases the object array index when a new object is created
Yes, Java makes a call when a new object is created, except it's not calling a method, it is calling a constructor. Constructors are declared like methods with no result type, and the name matching the name of the type, i.e. like this:
public class MyObject {
private int objCount = 0;
private int i = 0;
public class Property{..}
public Property propertyArray[] = new Property[12];
// This is the constructor
public MyObject() {
... // <<== Do stuff here
}
}
If you would like to add items to an array inside the MyObject class constructor, the array needs to be static: although constructors can access instance variables, each constructor gets a brand-new set of instance variables with which to work.
Related
I have an object, obj, of type MyObject, that I declare an instance of.
MyObject obj;
However, I don't initialize it. MyObject's Class looks something like:
public class MyObject {
public String i;
public String j;
public MyObject(String i) {
i = this.i;
}
}
So now, I want to set the value of j. So I say:
obj.j = "Hello";
Can I do this without having initialized obj? i.e. without saying:
obj = new MyObject("My i");
Will this object be null if I were to check the value of it, if I don't initialize it, or is setting a field within it enough to make it not null?
Thanks!
No, you cannot do that. You will have to create a new instance of MyObject if you want to access its fields.
Unless you make the fields static, ofcourse.
Do note that having your fields public violates encapsulation. You should make them private (or protected, if it's appropriate) and use getters and setters to provide access.
Sidenote:
public MyObject(String i) {
i = this.i;
}
This will not do what you want.
You have to assign the parameter i to the field variable i, not the other way around.
public MyObject(String i) {
this.i = i;
}
I've been looking for the answer to this problem all day.
I have a value class that holds a variety of values as long as the program is running.
I create a new Value object in class A, and store an int value.
Class A also has a printMoney() method.
public class A {
Value value = new Value();
value.setMoney(100);
public void printMoney {
System.out.println(value.getMoney);
}
In class B, I want to be able to call printMoney() from class A, so logically I do the following:
public class B {
A a = new A();
a.printMoney();
}
This does, however, return '0' as a value instead of '100'.
I understand that by creating an A object, I automatically create a new value object, which has its default money value. So, basically my question is; how do I solve this?
Make the object static. static Value value = new Value();
static variables are shared across all the objects
So the change made in static variable will be reflected for all the objects of class.
if you want to get that value in A you have to assign the value in A construtor, like
public class A {
Value value = new Value();
public A() {
this.value.setMoney(100);
}
otherwise, you can make the value static
you should receive the instance that creates the object B and save it then you would be able to call it
like so:
public class A {
B b = new B(this);
}
public class B {
A a;
public B(A a) {
this.a = a;
}
private someMethod () {
a.printMoney();
}
}
If I have a constructor
public class Sample {
public static StackOverflowQuestion puzzled;
public static void main(String[] args) {
puzzled = new StackOverflowQuestion(4);
}
}
and inside the main method of a program i have
public class StackOverflowQuestion {
public StackOverflowQuestion(){
//does code
}
public StackOverflowQuestion(int a){
this();
}
}
Is this creating an instance of StackOverflowQuestion via constructor2 and then creating another instance of StackOverflowQuestion via constructor 1 and therefore i now have two instances of StackOverflowQuestion directly inside each other?
Or does constructor2 in this case kind of laterally adjust and then instead create an instance of StackOverflowQuestion via constructor1 ?
I think you mean:
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
And call it like:
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
This will only create one object, because new is executed only once. The call this() will execute the code in the other constructor without creating a new object. The code in that constructor is able to modify the currently created instance.
It only creates one instance. One use case of it is to give default values for constructor parameters:
public class StackOverflowQuestion
{
public StackOverflowQuestion(int a) {
/* initialize something using a */
}
public StackOverflowQuestion() {
this(10); // Default: a = 10
}
}
this() is not the same as new StackOverflowQuestion()
this(5) is not the same as new StackOverflowQuestion(5)
this() and this(5) calls another constructor in the same class.
Therefore in this example:
public class StackOverflowQuestion
{
private int x;
private int y;
private int a;
public StackOverflowQuestion(){
this.x = 1;
this.y = 2;
}
public StackOverflowQuestion(int a){
this();
this.a = a;
}
}
The call to this() will just initialize the object and not create a new instance. Remember new StackOverflowQuestion(5) has been called already invoking the constructor which actually creates a new instance of the StackOverflowQuestion object
A constructor does not create an object. It just initializes the state of the object. It's the new operator which creates the object. Read through Creation of New Class Instance - JLS. Now what does this mean :
public class StackOverflowQuestion
{
public StackOverflowQuestion(){ // constructor
//does code
}
public StackOverflowQuestion(int a){ // another constructor
this();
}
}
StackOverflowQuestion puzzled = new StackOverflowQuestion(4);
A new object of StackOverflowQuestion is created by the new operator, just before a reference to the newly created object is returned as the result and assigned to the StackOverflowQuestion puzzled reference variable , the constructor StackOverflowQuestion(int a) makes a call to this() i.e. public StackOverflowQuestion(), code(if any) inside the default constructor runs and the control comes back to `StackOverflowQuestion(int a), the remaining code(if any) inside that is processed to initialize the new object.
The instance of a class is created at the moment you use the "new" operator. It is perfectly possible to create a class without constructors, because in that case, by default, the constructor with no parameters is available.
The "this" keyword just points to THIS specific object, so calling "this()" means "call my own constructor function, the one without parameters and execute what's inside"
When creating a method inside a class if you use the parameter:
public String Method(ClassName NewObject){}
or in my example below:
public String EqualsTo(Deck aCard){}
will it create a new object of that class within that method? If not anyone mind explaing what I is happening with that parameter?
NOTE: Disregard any minor syntax errors as I just constructed this to get my question across better so this is not a complete class.
import java.util.Scanner;
import java.util.Random;
public class Deck {
private int suit;
private int rank;
private Random generator = new Random();
Scanner in = new Scanner(System.in);
//Default constructor
public Deck() {
suit = suit.random(4);
rank = rank.random(13);
}
public String EqualsTo(Deck aCard){}
}
Objects are created when you use the new keyword. On the other hand, when you declare a method as
public String EqualsTo(Deck aCard){}
it says that the EqualsTo() method takes a Deck reference as a parameter. In order to use the method, you need to create a Deck object and keep a reference to it. Then you send the reference to the method.
That parameter act as a place holder for that type of object. It doesn't actually create it, the method signature says:
I'm an EqualsTo() method and I take/require a Deck type of instance/object as a parameter.
It return a String as a result.
By the way, I recommend using a boolean as the return type instead of a 'String' for an EqualsTo method.
Fundamental thing: Java is pass by value.
A new object is not created.
Object reference value created by the calling entity is copied to the method argument aCard.
Any modifications done on this object will remain visible to the calling entity. This is because the reference value is pointing to the same address location of the object.
Here's an example.
public class Test2 {
public int bla;
public static void main(String[] args) {
Test2 test = new Test2();
test.bla = 878;
test.doSome(test); // Calling Location
System.out.println(test.bla);
}
public void doSome(Test2 test) {
test.bla = 95;
}
}
NO
public String EqualsTo(Deck aCard){}
Does not create a new object when it is called.
Here is where the objects are created. Use case
Deck deck1 = new Deck(); // NEW OBJECT CREATED
Deck deck2 = new Deck(); // NEW OBJECT CREATED
String result = deck1.EqualsTo(deck2); // NO NEW OBJECT CREATED,
// JUST PASSED REFERENCE OF EXISTING OBJECT
// (except the result of course, which is probably a new object)
public class FooClass {
BarClass bar = null;
int a = 0;
int b = 1;
int c = 2;
public FooClass(BarClass bar) {
this.bar = bar;
bar.setFoo(this);
}
}
public class BarClass {
FooClass foo = null;
public BarClass(){}
public void setFoo(FooClass foo) {
this.foo = foo;
}
}
elsewhere...
BarClass theBar = new BarClass();
FooClass theFoo = new FooClass(theBar);
theFoo.a //should be 0
theBar.foo.a = 234; //I change the variable through theBar. Imagine all the variables are private and there are getters/setters.
theFoo.a //should be 234 <-----
How can I pass an object to another class, make a change, and have that change appear in the original instance of the first object?
or
How can I make a cycle where one change to a class is reflected in the other class?
That's already exactly how objects work in Java. Your code already does what you want it to.
When you pass theBar to the FooClass constructor, that's passing the value of theBar, which is a reference to a BarClass object. (theBar itself is passed by value - if you wrote foo = new FooClass(); in the BarClass constructor, that wouldn't change which object theBar referred to. Java is strictly pass-by-value, it's just that the values are often references.)
When you change the value within that object using theBar.foo.a, then looking at the value of a again using theFoo.a will see the updated value.
Basically, Java doesn't copy objects unless you really ask it to.