How can i access variable of one method into another? - java

I am creating android application. I have created one method testMethod1() then I have created another method testMethod2(). i have declare object of class in testMethod1(). How can i access object obj in testMethod2() ?
Public class TestClass() {
public void testMethod1() {
final ModalClass obj = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'obj' here
}
}
Edited quetion
I have created modal for listview. i want to set data into listview as bellow. but i can not be able to access locationDet into another method. its displaying can not resolve symbol 'locationDet'.
Public class TestClass() {
private List<LocationDetailModel> LocationDetailList = new
ArrayList<LocationDetailModel>();
public void testMethod1() {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
final LocationDetailModel locationDet = new LocationDetailModel();
locationDet.setTitle(obj.getString("name"));
testMethod2();
LocationDetailList.add(locationDet);
}
}
public void testMethod2() {
//I want to access 'obj' here
locationDet.setRating(results.getInt("rating"));
}
}

You have two choices:
1. You make the Variavble class known like this:
Public class TestClass(){
final ModalClass var = new ModalClass();
public void testMethod1() {
var = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'var' here
}
}
or you give your Var to test methode2 like this:
Public class TestClass()
{
public void testMethod1() {
final ModalClass var = new ModalClass();
testMethod2(var);
}
public void testMethod2(ModalClass var) {
//I want to access 'var' here
}
}

You can make the ModalClass var as a private attribute:
Public class TestClass(){
private final ModalClass var;
public void testMethod1() {
this.var = new ModalClass();
testMethod2();
}
public void testMethod2() {
//I want to access 'var' here
}
}

You can access the variables which are in scope and are visible. In your case you have a local variable which you wish to use in another method.
You can pass it as a method parameter. For this you will need to modify the signature of the method as below
public void testMethod2( LocationDetailModel locationModelDet ){
// now you acess the locationModelDet
}
and you can pass locationDet as parameter to the testMethod2 as testMethod(locationDet)
Another alternate option is instead of using local variable you may create a instance variable as
private LocationDetailModel locationDet = new LocationDetailModel();
Now in testMethod1() you need not create a local variable you can simply just set the title. For this you need not modify the signature of your testMethid2(). You will be able to acess the locationDet in both the method.

Related

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.

Passing parameter to anonymous class in Java

i'm trying to write anonymous inner class
interface Face{
void seeThis(String what);
}
class Eyes {
public void show(Face f){}
}
public class Seen {
public void test() {
Eyes e = new Eyes();
e.show(new Face() {
#Override
public void seeThis(String what){
System.out.print(what);
}
});
public static void main(String[] args) {
Seen s = new Seen();
s.test();
}
}
How to call seeThis() and how to pass parameter to it?
Method seeThis() belongs to Face class, which instance is anonymous and thus cannot be reached without storing reference to it. If you want to store a reference, you can do this in the following way:
public class Seen {
public Face face;
....
this.face = new Face() { ... };
e.show(this.face);
And then,
Seen s = new Seen();
s.face.seeThis();
Now, regarding passing the parameter. You have two options - declare parameter outside of anonymous class and make it final in order to be reachable by this anonymous class, or replace anonymous class with normal one and pass the parameter to its constructor:
Approach one:
final int parameter = 5;
...(new Face() {
#Override
public void seeThis() {
System.out.println(parameter);
}
});
Approach two:
public class MyFace implements Face() {
private final int parameter;
public MyFace(int parameter) {
this.parameter = parameter;
}
#Override
public void seeThis() {
System.out.println(parameter);
}
}
Then,
...
e.show(new MyFace(10));

How to read and write to variables of an abstract class

Put simply, I have an abstract class containing several variables and methods. Other classes extend this abstract class, yet when I try to read the private variable in the abstract class by calling getter methods inside the abstract class, it returns null as the value of the variable.
public class JavaApplication {
public static void main(String[] args) {
NewClass1 n1 = new NewClass1();
NewClass2 n2 = new NewClass2();
n1.setVar("hello");
n2.print();
}
}
public class NewClass1 {
public String firstWord;
public void setVar(String var) {
firstWord = var;
}
public String getVar () {
return firstWord;
}
}
public class NewClass2 extends NewClass1{
public void print() {
System.out.println(makeCall());
}
public String makeCall() {
return getVar();
}
}
Still prints out null.
Until the String is initialized, it will be null. You should probably have a constructor in the abstract class to set it.
public abstract class Command
{
String firstWord; // = null
protected Command(){}
protected Command( String w )
{
firstWord = w;
}
//...
}
public class Open extends Command
{
public Open()
{
this( "your text" );
}
public Open( String w )
{
super( w );
}
// ...
}
If you need to modify the firstWord string everytime execute() is called then it may not be necessary to use a constructor with a String parameter (I added a default constructor above). However, if you do it this way then either
You must make sure setFirstWord() is called before getFirstWord(), or,
Handle the case when getFirstWord() returns null. This could be by simply using a default value (maybe determined by each subclass) or something else, like failing to execute.
As I do not know all the details of your implementation I cannot tell you further information.

Trouble with constructor in the Processing Java environment

I am new to Java and working in the Processing environment. I want to create a class that has a few objects in it, but I am getting an error when I try to construct those classes' object.
The bzaVertex is supposed to be an object within the bza object, but when I seemingly try to construct it, Processing says "The constructor sketch.BzaVertext(int) is undefined." I don't understand how Bza is getting its constructor called properly, but not the child object -- I seem to be calling them the same way?
I have this code all in the main class. I'm using Processing 2.0b7. What am I doing wrong?
Bza bza;
void setup() {
bza = new Bza();
}
public class BzaVertex {
public void BzaVertex(int d) {
}
}
public class Bza {
BzaVertex v1;
public void Bza() {
v1 = new BzaVertex(4);
}
}
constructors do not have a return type so you need to to remove the void from both of them
class BzaVertex {
public BzaVertex(int d) {
}
}
class Bza {
BzaVertex v1;
public Bza() {
v1 = new BzaVertex(4);
}
}
public class Main
{
public static void main(String[] args)
{
Bza bza;
bza = new Bza();
}
}
that should solve the error

Java: get results from anonymous class operation

I want to do something like this:
public class ScadenzaService {
...
public List<Scadenza> tutteLeScadenze() {
List<Scadenza> scadenze = null;
txm.doInTransaction(new TransactionAction() {
#Override
public void perform() {
scadenze = dao.getAll(Scadenza.class);
}
});
return scadenze;
}
But I can't access scadenze in the inner class, since it's not final. However, final wouldn't help: it makes a constant.
What's the workaround?
Make scadenze final and initialise it to a new List. Inside your anon class you can still add to the list; being declared final does not prevent this.
public List<Scadenza> tutteLeScadenze() {
final List<Scadenza> scadenze = new ArrayList<Scadenza>();
txm.doInTransaction(new TransactionAction() {
#Override
public void perform() {
scadenze.addAll(dao.getAll(Scadenza.class));
}
});
return scadenze;
}

Categories

Resources