How to access object not stored in variable - java

I have this method that I pass a newly created object into
foo(new WebObject());
How do I get access to the WebObject to use in another object? In other words where do newly created objects reference go?

That depends on what you mean - if you mean to say that you want to use it later, after the function call, then you want to do something like
WebObject wObj = new WebObject();
foo (wObj);
WebObject nObj = wObj;
If, however, you mean you want to use the object within the foo(WebObject) method, then what you need to do is, within the function, something more along the lines of
foo (WebObject obj)
{
WebObject local = obj;
}

Store it in a variable!
WebObject whatever = new WebObject();
foo(whatever);
bar(whatever);

as user2357112 posted you can assign new object to a local variable and pass it via few methods
WebObject instance= new WebObject();
foo(instance);
foo2(instance);
System.out.println(instance);
but if you're looking something else, you might assign it to a supporting class
public class WebObjectKeeper{
private static WebObject instance=null;
public static void setWebObject(WebObject obj){
this.instance=obj;
}
public static WebObject getWebObject(){
return instance;
}
}
and then you use it in code like:
public void myMethod(){
WebObjectKeeper.setWebObjcet(new WebObject());
foo(WebObjectKeeper.getWebObject());
foo2();
}
public void foo2(){
WebObjectKeeper.getWebObject().executeThisMethod();
System.out.println("Object = " + WebObjectKeeper.getWebObject());
}

Related

Why cannot I assign a value to the object reference being returned by a method?

I have a function which returns a reference to an object. Why cannot I assign this returned reference to point to another object? The reference being returned by the function is not final , hence I should be allowed to change it's value to point to another object.
class TestClass3 {
public TestClass3 hello() {
TestClass3 t = new TestClass3();
return t;
}
}
class TestClass1 {
public static void main(String[] args) {
TestClass3 obj = new TestClass3();
// The below line of code gives an error
obj.hello() = null;
}
}
I expect that the reference returned by calling the hello() method should be assigned null value.
You'll need to assign obj.hello() to a variable, which you can then set to null if you want.
Here in your code when you write obj.hello(), it only call the method hello. It doesn't assign the return of hello to any variable. So no variable is actually holding the return value of the method hello. While you can assign null value to same variable. That's why it's not a valid syntax.
Valid syntax should be like:
TestClass3 value = obj.hello();
value = null;
Simply speaking, it's because Java doesn't allow it while there are languages that do (e.g Python). In Java you cannot monkey-patch existing code.
Why? Well, Java wasn't born as a functional language, so while considerable for function references was added in Java 8, they're still not first class citizens. So you cannot assign a new value to a method of a class like you can with a field of that class.
However, since you can assign values to fields, you could do something like this:
class TestClass3 {
public Supplier<TestClass3> hello;
public TestClass3() {
this.hello = this::hello;
}
public TestClass3 hello() {
TestClass3 t = new TestClass3();
return t;
}
}
class TestClass1 {
public static void main(String[] args) {
TestClass3 obj = new TestClass3();
obj.hello.get(); // calls hello()
obj.hello = null; // now works
}
}
Here I define a member named hello in TestClass3. It's of type Supplier<TestClass3>, and it just so happens that public TestClass3 hello() is of the same type. Hence, in the constructor of TestClass3 I can do this: this.hello = this::hello;.
Now we have a reference to hello() as a field, which means that we can invoke the function using that field, or even change the field's value:
obj.hello.get();
obj.hello = null;
obj.hello() is an object's behavior, not a reference, only reference can be set to null.
About null:
null is just a reference value.
reference is a variable that has a name and can be used to access an object by referring to the memory address where it is located.
About Object:
All objects have three essential features:
state
behavior
identity
You are trying to set the method to a value, this isn't possible and doesn't make any sense, if you think about it. If you want to save the reference returned by obj.hello(), write
TestClass3 obj2 = obj.hello();

Initializing an object in a method in Java

Suppose I want to have a bunch of private static objects in a class, but they are complicated objects and I would like to use a specific function to initialize them with some parameters. Ideally, I would write code like this:
public class TestClass{
private Class ComplicatedObject{
private int anInteger;
private String aString;
public ComplicatedObject(int inputInt,String inputString){
anInteger = inputInt;
aString = inputString;
}
public void someMethod(){
//do a thing
}
}
private void MakeAThing(ComplicatedObject theThing, int someInt,int someString){
theThing = new ComplicatedObject(someInt,someString);
//do extra stuff that one might want to do here
}
private static ComplicatedObject IMPORTANT_OBJECT;
public TestClass(){
MakeAThing(IMPORTANT_OBJECT, 0,"Test");
IMPORTANT_OBJECT.someMethod();
}
}
This will crash because (as far as I understand Java) when I call someMethod() on IMPORTANT_OBJECT, IMPORTANT_OBJECT is actually null - the MakeAThing method did create a new object, but only its internal reference (theThing) actually referenced the new object. The reference for IMPORTANT_OBJECT is still null.
Is there any way I can write a method that will change the reference for IMPORTANT_OBJECT to reference a new object?
(yes, I know that one easy solution would be to just say IMPORTANT_OBJECT = new Object(); and then add the parameters later, but this will make my code really messy (there are many "important objects") and if there is another way I'd much prefer it.)
How about function that return new ComplicatedObject:
private ComplicatedObject MakeAThing(int someInt,int someString){
return new ComplicatedObject(someInt,someString);
}
And just initialize the IMPORTANT_OBJECT in TestClass constructor
public TestClass(){
IMPORTANT_OBJECT = (0,"Test");
IMPORTANT_OBJECT.someMethod();
}
Or have I misunderstood the question?

How to pass a created object to another class Java

I have created an instance of an object in one of my classes for a Java program. How can I pass the same instance of that object to another class?
Would I need to do something like creating some type of a getter method in the original class to pass the object through to the other class?
To "pass" it you need a method or a constructor in the other class that can accept it:
public class Other {
// either
public Other(MyClass obj) {
// do something with obj
}
// or
public void method(MyClass obj) {
// do something with obj
}
}
Then call the constructor/method:
MyClass x = new MyClass();
Other other = new Other();
other.method(x);
There are many ways to pass the reference for one object to another object. The simplest and most common ways are:
as a constructor parameter,
as a parameter of a setter method; e.g. setFoo(Foo foo) to set the "foo" attribute, or
as an "add" method in the object being passed is going to be added to a collection; e.g. addFoo(Foo foo).
Then there are a variety of more complicated patterns where objects are passed using publish/subscribe, call-backs, futures, and so on.
Finally there are some tricks that can be used to "smuggle" objects across abstraction boundaries ... which are generally a bad idea.
You can pass the object via the constructor of the other class.
Simple Example:
Class A{
}
Class B{
A a;
public B(A obj){
this.a=obj
}
}
Let's assume you want to pass an object of class A to class B. Now you have created the object like this:
A object = new A ();
And now in your B class, you can write a method to accept a A object. It should be public and you can make it static if you like.
If you want to pass object to B, you must want to do something with it, right? So you should name your method accordingly. You probably want to assign a field of type A (Let's call this fieldA) in B. (or maybe that isn't what you want, but I'll use this for the example)
Let's look at the method:
public void setFieldA (A a) {
fieldA = a;
}
You can call this method as follows:
anObjectOfClassB.setFieldA (object);
Of course you don't need anObjectOfClassB if it is static.

set variable in calling object from object being called

In Java, how do you set variables in a calling object from the object that is being called? I guess I could set up some kind of struct class, but can someone show me if there is a simpler way to do it, such as some modification of the pseudocode below:
public class Example(){
int thisInt;
int thatInt;
public static void main(String[] args){
Another myAnother = new Another();
}
setThisInt(int input){thisInt=input;}
setThatInt(int input2){thatInt=input2;}
}
public class Another(){
void someFunc(){
this.Example.setThisInt(5);//I know this syntax is wrong
this.Example.setThatInt(2);//I know this syntax is wrong
}
}
Pass in a reference to the object.
public class Another{
void someFunc(Example ob){
ob.setThisInt(5);
ob.setThatInt(2);
}
}
If you're using nested classes(one class inside the other with an implied parent-child relationship), use:
OuterClass.this.setThisInt(5);
and so on.

Using a setter from outside a form?

I am trying to access a form which is not static from another class which is also not static. I'd like to use a member in the class....
Public Class MainForm
public void setConsoleText(String Text){
jTextArea1.append(Text);
}
I need to know a way to reference this setter from my class "Log" which is basically where data goes to be parsed and logged. I want it to be like this:
private void consoleOut(String data) {
System.out.println(data);
MainForm.setConsoleText("data");
}
I cannot access this method.. I can only access MyForm.Class. Is there a way to reference the one that's been instantiated, or all of them in this virtual machine? It really doesn't matter as there will only be one of these running in this instance of the Java VM.
I just can't seem to figure this one out.
You need to give Log a non-static MainForm variable and pass reference to the currently visualized MainForm object into the Log class and into this variable. This can be done via a Log constructor parameter or via a setter method. Then you can call methods on this instance (but checking that it's not null first). Something like:
public class Log {
private MainForm mainForm; // our MainForm variable
public Log(MainForm mainForm) {
// setting the MainForm variable to the correct reference in its constructor
this.mainForm = mainForm;
}
private void consoleOut(String data) {
System.out.println(data);
if (mainForm != null) {
// now we can use the reference passed in.
mainForm.setConsoleText("data");
}
}
}
Edit 1
For instance if you create your MainForm object and display it from a main method somewhere, create Log along with it and pass the visualized MainForm into the Log constructor, something like so:
public static void main(String[] args) {
MainForm myMainForm = new MainForm();
// ... whatever code is necessary to set up the
// ... MainForm object so it can be visualized
myMainForm.setVisible(true); // and show it
Log myLogObject = new Log(myMainForm);
//...
}
Note that if this doesn't help you, you'll need to post more of your code.

Categories