如何在不同方法之间使用相同的对象

时间:2014-07-12 11:50:20

标签: java oop

我是Java编码的新手。

我想知道如何在不同方法之间传递相同的对象?

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

从上面的代码中,我如何使用Method1()中创建的对象可以在Method2中使用?

这是我的实际代码:

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

我在这里看到的问题,writeHeader工作正常,但在执行writeReport时我得到NullPointer异常。如何克服这个?

java.lang.NullPointerException
    at UtilityFunctions.writeReport(UtilityFunctions.java:71)
    at TempClass.writeDetailedReport  etc.........

3 个答案:

答案 0 :(得分:0)

以下是如何将对象从一种方法传递到另一种方法

 public void method1()
      {
        Object objToBePassed=new Object();
        method2(objToBePassed);
      }

      public void method2(Object passedObject)
      {
        // your logic
      }

答案 1 :(得分:0)

您应该在类的构造函数中创建对象,然后您可以轻松地使用此对象。例如:

class YourClass {
   private Object obj;
   public YourClass() { //constructor
      obj = new Object();
   }
   public void method() {
      //your logic
   }

总而言之,如果在构造函数中创建类的字段,则不必担心空指针,并且所有类方法都可以访问这些对象。如果你想在你的类之外使用私有字段,例如在其他类的方法中你应该使用getter方法并在参数中传递对象:

public void otherMethod(Object obj)

答案 2 :(得分:0)

首先将您的对象声明为您班级的字段:

class MyClass
{
    private Object obj;

    //...Rest of class goes here
}

在构造函数中初始化对象,以便在您想要访问它时它不为null。

public MyClass()
{
    this.obj = new Object();
}

现在您可以根据需要从两种方法中访问它。

public method1()
{
    this.obj.doSomething();
}
public method2()
{
    this.obj.doSomethingElse();
}

总而言之,它看起来像这样:

class MyClass
{
    private Object obj;

    public MyClass()
    {
        this.obj = new Object();
    }

    public method1()
    {
        this.obj.doSomething();
    }

    public method2()
    {
        this.obj.doSomethingElse();
    }

}

现在,如果您想将一个对象从一个方法实际传递到另一个方法但又不希望任何其他方法可以访问它,您可以将其设为如下参数:

public method1(Object obj)
{
    obj.doSomething()
}

然后你可以从其他地方调用该方法传递对象类型的特定实例。

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
}

如果要多次调用单个方法,但是让它作用于不同的输入,则传递参数特别有用。