Increasing the scope of object from local scope - java

I want to create an object using a method but I want it (object+reference) to live even after the method ends. Example of code:
public class start{
public static void main (String [] Args){
public void createObject(){
object1 createdObject = new object1();
}
createObject();
createdObject.doSomething();
}
}
public class object1{
//code for object 1
}
So my main question is: how to create object using method and let it live even after method ends. The problem is that reference createdObject is popped of stack after method ends and therefore I can't use it anymore. Is it even possible to create object for further use this way?

public class start{
public static void main (String [] Args){
//class level scope
object1 createdObject = null;
private void createObject(){
createdObject = new object1();
}
}
public class object1{
//code for object 1
}
NOTE: I have not following naming conventions. But please follow them in actual code
UPDATE: Proper code check it out
public class Main {
public static void main(String[] args) {
new MyClass().doSomething();
}
}
class MyClass{
Object obj ;
public void doSomething(){
createObject();
}
private void createObject(){
obj = new Object();
System.out.println("Created MyClass instance");
}
}

Your method should return object1 instead of void and you have to add the following line at the end of the method:
return createdObject;

Related

Return value to an Object reference

I'm new to Selenium java and currently learning object reference and returns
I was trying to code this logic wherein I declare a non static variable in main class, declare an object for it, use that object in another class and return it to main class
My problem is when i return it back to main class it outputs 0. Is this scenario possible? or am I doing something wrong
package ReturnType;
public class Class1 {
public int Mul(int i, int j) {
Class2 cc = new Class2();
cc.c=i*j;
return cc.c;
}
}
Here is my main class
package ReturnType;
public class Class2 {
public int c;
public static void main(String[] args) {
Class1 xp = new Class1();
Class2 cc = new Class2();
xp.Mul(2,3);
System.out.println(cc.c);
}
}
Almost got the result... the return of the method is getting lost, you have to assign it to something
public class Class2 {
public int c;
public static void main(String[] args) {
Class1 xp = new Class1();
Class2 cc = new Class2();
cc.c = xp.Mul(2,3); //here assign it
System.out.println(cc.c);
}
}

How to call a behavioral method from main method in java?

I have a non static method abc() in the class that contains main() method. Now how to call this method abc() from main. Can i create an instance of the class in the same class?
public class A
{
public static void main(String[] args)
{
//how to call abc() here?
}
private int abc()
{
return 2;
}
}
You have to instanciate current class, use this code:
public static void main(String[] args)
{
A a = new A();
int value = a.abc();
}

How to use same object between diffrent methods

I am novice to Java coding.
I wanted to know how to pass the same object between different methods?
Ex:
Class A
{
//Declaring an object say
Object obj;
public void Method1()
{
//Here i want to use some method of obj
obj=new Object();
obj.Metod1();
}
public void Method2()
{
//Here i want to use another method of obj
obj.Metod2();
}
}
class B
{
A aObj=new A();
aObj.Method1();
aObj.Method2();
}
From the above code, how can i use the object created in Method1() can be used in Method2?
This is my actual code:
public class UtilityFunctions
{
File fileName;
public static FileWriter fwObj;
public static BufferedWriter bwObj;
Logger App_log;
UtilityFunctions()
{
fileName=new File(System.getProperty("user.dir")+"\\src\\TempFile.html");
Logger App_log=Logger.getLogger(UtilityFunctions.class);
try
{
if(!fileName.exists())
fileName.createNewFile();
this.fwObj=new FileWriter(fileName);
this.bwObj=new BufferedWriter(fwObj);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void writeHeader()
{
try
{
this.bwObj.append("<html><body><table border='1' style='widht:300px'><tbody><tr><th>Date</th><th>Position</th><th>Site</th></tr>");
this.bwObj.flush();
// this.bwObj.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void writeFooter()
{
try
{
this.bwObj.append("</html></body></table></tbody>");
this.bwObj.flush();
bwObj.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void writeReport(String strstrPositionName)
{
DateFormat format=new SimpleDateFormat("MM/dd/yyyy");
Date date=new Date();
String strCurrentDate=format.format(date);
try
{
String strFormattedString="<tr><td>"+strCurrentDate+"</td><td>"+strstrPositionName+"</td><td>SomeSite</td></tr>";
App_log.info("Printing the Line as: "+strFormattedString);
this.bwObj.append(strFormattedString);
this.bwObj.flush();
// bwObj.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I would like to call above methods like
Class TempClass
{
public static void main(String args[] args)
{
UtilityFunctions obj=new UtilityFunctions();
obj.writeHeader();
obj.writeReport("Message1");
obj.writeReport("Message2");
// I may add many write Report statements here.
obj.writeFooter();
}
}
The problem i see here, writeHeader is working fine, but at execution of writeReport I am getting NullPointer Exception. How to overcome this?
java.lang.NullPointerException
at UtilityFunctions.writeReport(UtilityFunctions.java:71)
at TempClass.writeDetailedReport etc.........
Here is how you can pass the object frome one method to another
public void method1()
{
Object objToBePassed=new Object();
method2(objToBePassed);
}
public void method2(Object passedObject)
{
// your logic
}
You should create your objects within constructor of the class, and then you can easly use this object. for example:
class YourClass {
private Object obj;
public YourClass() { //constructor
obj = new Object();
}
public void method() {
//your logic
}
To sum up, If you create fields of your class in constructor you don't worry about null pointers and all of class methods have access to those objects. If you want to use private field outside your class, for example in method from other class you should use getter method and pass object in argument:
public void otherMethod(Object obj)
First declare your object as a field for your class:
class MyClass
{
private Object obj;
//...Rest of class goes here
}
Initialize the object in your constructor so that it is not null when you want to access it.
public MyClass()
{
this.obj = new Object();
}
Now you can access it from your two methods as you wish.
public method1()
{
this.obj.doSomething();
}
public method2()
{
this.obj.doSomethingElse();
}
All in all, it can look something like this:
class MyClass
{
private Object obj;
public MyClass()
{
this.obj = new Object();
}
public method1()
{
this.obj.doSomething();
}
public method2()
{
this.obj.doSomethingElse();
}
}
Now if you want to actually pass an object from one method to another but don't want it to be accessible to any other methods, you can make it a parameter like this:
public method1(Object obj)
{
obj.doSomething()
}
And then you can call the method from somewhere else passing specific instances of the object type.
public method2()
{
Object obj1 = new Object();
Object obj2 = new Object();
this.method1(obj1); //All actions in method1 will be done to obj1
this.method1(obj2); //All actions in method1 will be done to obj2
}
Passing parameters is especially useful if you want to call a single method several times, but have it act on different inputs.

Java initial values?

If I were to do something such as:
public class Game
{
private boolean RUNNING = true;
Game()
{
}
public static void main(String[] args)
{
Game game = new Game();
}
}
At what point in time would RUNNING = true?
edit: for clarity, at what point in the program would running be set to true. ex: Before the constructor, after the constructor, etc.
It will be set to true before the constructor. You can use it in the constructor as true.
This code explains itself:
public class SuperClass
{
String superField = getString("superField");
public SuperClass()
{
System.out.println("SuperClass()");
}
public static String getString(String fieldName)
{
System.out.println(fieldName + " is set");
return "";
}
public static void main(String[] args)
{
new ChildClass();
}
}
class ChildClass extends SuperClass
{
String childField = getString("childField");
public ChildClass()
{
System.out.println("ChildClass()");
}
}
OUTPUT:
superField is set
SuperClass()
childField is set
ChildClass()
When the constructor is called using the new operator all non-static members of the class are initialized before the code inside the constructor is executed. You can use the debugger and step into that call and see where it goes first. Static members are initialized when the class is loaded and for the first time accessed (see this question for more detailed info about static members).
private boolean RUNNING = true;
Game() {
}
is exactly the same as
private boolean RUNNING;
Game() {
RUNNING = true;
}
Actually, the comiler will move the initialization at the beginning of the constructor. The value will then be set when instantiating an object of that class.
When you try to use local variables which not manually initialized, you will get a compile time error.
public static void main(String args[]){
int a;
System.out.pritnln(a); //error
}
But it's not the case with instance variables. This itself shows that they are ready for usage before the constructor even.
public class Example{
private int a;
public Example(){
System.out.println(a); //No error
}
public int getA(){
return a; //No error
}
}
I hope this intuition answers your question..........

Accessing variable from an inner class - getting null pointer exception

i want to access the arr variable from inside the inner class method MyMethod. When i try to print it from there i end up getting a null pointer exception.
public class MyClass{
String[] arr;
MyClass my;
public MyClass(){
my = new MyClass();
}
public class MyInner {
public void MyMethod() {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main(String[] args) {
String[] n={"ddd","f"};
my.arr=n;
}
}
You can use just arr. However until you set it to something it will be null
BTW: Your my = new MyClass() will blow up as it will create objects until it stack overflows.
You haven't initialized it yet, so the reference is null. Initialize it in your constructor for example, and you will have access to the variable via your inner class.
public class MyClass {
String[] arr;
public MyClass (String[] a_arr) {
arr = a_arr;
}
public class MyInner {
public void MyMethod () {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main (String[] args) {
String[] n= {"ddd","f"};
MyClass myClass = new MyClass (n);
}
}
Well, for starters in your main method you never create an instance of your class.
Also, MyClass has a reference to a MyClass object. In the constructor of MyClass, it initializes that reference by calling it's own constructor. That's an endless loop.
Do the following. Your way of initialization is wrong.
public class MyClass{
String[] arr;
MyClass my;
public MyClass(){
}
public class MyInner {
public void MyMethod() {
// I need to access 'my.arr' from here how can i do it.
}
}
public static void main(String[] args) {
String[] n={"ddd","f"};
MyClass my=new MyClass();
String[] b = new String[2];
System.arraycopy( n, 0, b, 0, n.length );
}
}
In case of more than 2 strings, simply do String[] b = new String[n.length];

Categories

Resources