Initializing an object in a method in Java - 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?

Related

How do I add an instance of type MyClass to an array of MyClass, declared in MyClass, inside the constructor of MyClass?

In order to keep track of instances, we have an array MyClass[] mc = new MyClass[5];
I want to save the instances of MyClass created inside this array, during the constructor call itself.
Something like this:
public class MyClass{
private static final int MAX_SIZE = 64;
private static int number = 0;
private static MyClass[] classList= new MyClass[MAX_SIZE];
public MyClass(MyClass mc) {
classList[number++] = mc;
}
public static void main(String[] args) {
MyClass mc1 = new MyClass(mc1);
}
But this doesn't work as I get "mc1 might not be initialized" error which is expected, tbh.
Now, I know we can create another method that to save the instance of created class inside the array but this 'saving instances of class' is in class's self interest and do not want to force users of class to call this method. Hence finding a way to finish this up in the const itself.
How do I go about doing this? Thank you very much in Advance!! :)
Asking for a friend.
You can do this in your constructor:
classList[number++] = this;
And simply not have that mc parameter.
But of course, the whole idea is bad practice. A class has a distinct responsibility. You are putting another responsibility in it (to count / list instances). So besides the fact that your code easily creates a memory leak, it also violates the single responsibility principle.
If you want to keep track of certain objects, then have a another class that holds such lists and explicitly register newly created objects there.
Using MyClass mc as a parameter in your constructor is a mistake. There is no way for that MyClass instance to be initialized as it keeps requiring another previous already initialized instance. As someone before me pointed out you can use ... = this and work around it, but its not advised. Just write the extra method.
You could do better using a list, such as an ArrayList. The performance of ArrayList is not much worse than that of an array.
public class ArrayTest {
private static List classList = new ArrayList<>();
public ArrayTest() {
classList.add(this);
}
public static void main(final String[] args) {
final ArrayTest mc1 = new ArrayTest();
}
}

How to access object not stored in variable

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());
}

How access private methods from anonymous class?

Suppose I have class:
MyObject b = new MyObject(){
private void method(){}
}
Is it possible to get method() by reflection? For toString I can write:
MyObject.class.getMethod("toString");
But what about for new created private method?
You have to invoke Object#getClass() on b reference to get the anonymous class, where the method is declared. MyObject.class will give you Class<MyObject>, which is not possibly what you want.
And then use Class#getDeclaredMethod() to get the private method:
Method method = b.getClass().getDeclaredMethod("method");
method.setAccessible(true);
method.invoke()
You can use it with:
Method method = b.getClass().getDeclaredMethod("method");
Here b.getClass() will return the class that the compiler generated for you for the anonymous inner class.
I can't easily imagine a situation in which that's a good approach, however.
Note that if you use a local named class, you don't even need to use reflection to call the method:
public class Test {
public static void main(String[] args) {
class Foo {
private void doSomething() {
System.out.println("Yes!");
}
};
Foo foo = new Foo();
foo.doSomething();
}
}
If you could give us more context about why you want this, we could probably be of more help in finding the best solution.

Define the methods of anonimous class created inside a method from the method caller

in a class i have
A a = new A(){
stuffhere
};
now i found that i need to create the new A inside a method and return it, but i have to define the stuffhere from the class caller. Is there a way in java to do so? Something like
A a = createAClass(){
stuffhere
};
public A createAClass()[T]{
return new A(){T};
}
or something similar. I would prefer not to use an interface to pass to the create method, since my anonymous classes not only override methods, but also adds attributes and new functions, and i don't think i can pass them with an interface..
Any thought?
EDIT for the -1ers (a simple comment would suffice)
with the syntax [T], obviously wrong, i meant something that can pass a generic code, let's say a copy-paste of code.
createAClass()[int a; String b; #override public void mymethod(){dosomethigb;} public void dosomethingelse(){dosomethingelse;}];
would work like
public A createAClass(){
return new A()
{
int a;
String b;
#override public void mymethod()
{dosomethigb;}
public void dosomethingelse()
{dosomethingelse;}};
};}
but if i write in another part of the program
createAClass()[float c; List d; public void yourmethod(){dosomething2;} #override public void dosomethingelse(){dosomethingelse2;}];
it would instead work like
public A createAClass(){
return new A()
{
float c;
List d;
public void yourmethod()
{dosomething2;}
#override public void dosomethingelse()
{dosomethingelse2;}
};}
My bad, i choose a bad may of making an example, but i thought it was the clearest way. Maybe i should have used X instead of T?..
Long story short:
i want create an anonymous class inside a method, but define what the anonymous class does in the method caller, and not inside the method(like the title says)
EDIT2:
i know i can't access the new methods from the class, what i do now is create an anonymous class, add a few attributes and method, and then use them in an overridden method. The added methods are not a problem, since i can make the method caller to pass an interface that is called by the overridden method in the anonymous class created, the problems are the attributes. I don't know how to add them in the anonymous class passing them from the method caller.
Something like the following usually works:
public A createAClass(final String value){
return new A(){
// some code here that can access value
};
}
If you are looking for something else, please clarify the question.
Edit
Answer is no you can't do that. You are trying to create an A with no defined API for A. Even if you could do what you propose, how would any user of A know what methods / fields are available if A is not defined somewhere? For A to be useful, you need to have an API that A implements.
Not sure whether fully understood by me. But the pattern is like this:
public class Here {
private int stuff;
public class A {
private A() { ... }
... ++stuff; ...
}
public A createA() { ... }
}
...
Here here = ...
A a = here.createA();
AFTER QUESTION EDITED:
The simplest way is to override a method:
final Object stuff = ...;
A a = new A() {
#Override
protected void onSomeEvent() {
... stuff.toString();
}
}
Then A can call onSomeEvent.

What use is the final modifer on method/constructor parameters

Hello
What use is the final modifier on a method/constructor parameter?
Ex:
class someClass {
private final double some; // I understand the use of final in this context, immutability etc..
public someClass(final double some) {
// I don't understand what purpose is served by making "some" final
this.some = some;
}
public void someMethod(final double some) {
// I don't understand what purpose is served by making "some" final
}
}
There are 2 main situations when you need it:
1) you want to use the parameter inside local class (usually, anonymous class), like:
public void foo(final String str) {
Printer p = new Printer() {
public void print() {
System.out.println(str);
}
};
p.print();
}
2) you like the style when every variable which is not modified is marked with the final word (it is generally a good practice to keep as much things immutable as possible ).
Well, the purpose is that you cannot asign the parameter with anything
public someClass(T some) {
some = null; //You can do this. Maybe you want to use the variable `some` later on in your constructor
}
public someClass(final T some) {
some = null; //You can't do this. If you want to reuse `some` you can't.
}
Useful? Not much. Normally you don't use arguments variables. But in some special situations you may want to be able to do it.
Anyway, if some does new someClass(mySome) , mySome will never be changed although inside the function you assign values to the argument. There is no such thing as pass-by-refrence in Java. Variables are primitives or references to objects, never the object itself.
From the point of view of the function, the some variable is a constant.
Another benefit would be to prevent variable reuse. That is to say "some" should be used for only one purpose.

Categories