调用类的方法而不创建它的对象

时间:2014-10-09 05:28:45

标签: java

class A{
    String z(){
        System.out.println("a");
        return "sauarbh";
    }
}
class B{
    A a;
    A x(){
    return a;   
    }
}
public class runner {
    public static void main(String[] args) {
        B b = new B();
        A a2=b.x();
        a2.z(); // Calling A class method without creating object of it
    }
}

另一个例子

class Person
   {
   private String lastName;
   private String firstName;
   private int age;
//--------------------------------------------------------------
   public Person(String last, String first, int a)
      {                               // constructor
      lastName = last;
      firstName = first;
      age = a;
      }
//--------------------------------------------------------------
   public void displayPerson()
      {
      System.out.print("   Last name: " + lastName);
      System.out.print(", First name: " + firstName);
      System.out.println(", Age: " + age);
      }
//--------------------------------------------------------------
   public String getLast()           // get last name
      { return lastName; }
   }  // end class Person
////////////////////////////////////////////////////////////////
class ClassDataArray
   {
   private Person[] a;               // reference to array
   private int nElems;               // number of data items

   public ClassDataArray(int max)    // constructor
      {
      a = new Person[max];               // create the array
      nElems = 0;                        // no items yet
      }
//--------------------------------------------------------------
   public Person find(String searchName)
      {                              // find specified value
      int j;
      for(j=0; j<nElems; j++)            // for each element,
         if( a[j].getLast().equals(searchName) )  // found item?
            break;                       // exit loop before end
      if(j == nElems)                    // gone to end?
         return null;                    // yes, can't find it
      else
         return a[j];                    // no, found it
      }  // end find()
//--------------------------------------------------------------                                    // put person into array
   public void insert(String last, String first, int age)
      {
      a[nElems] = new Person(last, first, age);
      nElems++;                          // increment size
      }
//--------------------------------------------------------------
   public boolean delete(String searchName)
      {                              // delete person from array
      int j;
      for(j=0; j<nElems; j++)            // look for it
         if( a[j].getLast().equals(searchName) )
            break;
      if(j==nElems)                      // can't find it
         return false;
      else                               // found it
         {
         for(int k=j; k<nElems; k++)     // shift down
            a[k] = a[k+1];
         nElems--;                       // decrement size
         return true;
         }
      }  // end delete()
//--------------------------------------------------------------
   public void displayA()            // displays array contents
      {
      for(int j=0; j<nElems; j++)       // for each element,
         a[j].displayPerson();          // display it
      }
//--------------------------------------------------------------
   }  // end class ClassDataArray
////////////////////////////////////////////////////////////////
class ClassDataApp
   {
   public static void main(String[] args)
      {
      int maxSize = 100;             // array size
      ClassDataArray arr;            // reference to array
      arr = new ClassDataArray(maxSize);  // create the array
                                     // insert 10 items
      arr.insert("Evans", "Patty", 24);
      arr.insert("Smith", "Lorraine", 37);
      arr.insert("Yee", "Tom", 43);
      arr.insert("Adams", "Henry", 63);
      arr.insert("Hashimoto", "Sato", 21);
      arr.insert("Stimson", "Henry", 29);
      arr.insert("Velasquez", "Jose", 72);
      arr.insert("Lamarque", "Henry", 54);
      arr.insert("Vang", "Minh", 22);
      arr.insert("Creswell", "Lucinda", 18);

      arr.displayA();                // display items

      String searchKey = "Stimson";  // search for item
      Person found;
      found=arr.find(searchKey);
      if(found != null)
         {
         System.out.print("Found ");
         found.displayPerson();
         }
      else
         System.out.println("Can't find " + searchKey);

      System.out.println("Deleting Smith, Yee, and Creswell");
      arr.delete("Smith");           // delete 3 items
      arr.delete("Yee");
      arr.delete("Creswell");

      arr.displayA();                // display items again
      }  // end main()
   }  // end class ClassDataApp

在上面的代码中,我调用类A的z()方法,引用a2而不创建类A的对象,因为我是java的新手,我想知道在显示的代码中java中的这个概念是什么?现在我只知道如果我们想要在不创建对象的情况下调用方法,我们必须将该方法设置为静态。

在使用人参考的第二个例子中发现我们能够调用displayPerson()方法而没有空指针异常

3 个答案:

答案 0 :(得分:4)

致电:

String z(){
        System.out.println("a");
        return "sauarbh";
    }

没有类A的对象,方法z必须是静态的:

static String z(){
        System.out.println("a");
        return "sauarbh";
    }

所以改变你的代码如下:

class A{
    static String z(){
        System.out.println("a");
        return "sauarbh";
    }
}
class B{
    A a;
    A x(){
    return a;   
    }
}
public class runner {
    public static void main(String[] args) {
         B b = new B();
         b.x();
         A.z();
    }
}

输出

a

答案 1 :(得分:1)

是,如果您想调用该方法,则应该使用static关键字来实例化该类。

你在这做什么?

您间接尝试获取A的实例。但是在这种情况下,您将获得NullPointerException,因为您只返回A

的引用(变量)
B b = new B();
A a2=b.x();
a2.z(); // NullPointerException from here

NPE?

class B{
  A a;
  A x(){
   return a;   // you just return the reference 
   // it should be return new A();
  }
 }

为了您的编辑:

查看insert()方法。它正在创建Person实例。

答案 2 :(得分:0)

B类方法x()没有返回A的新对象。相反,您返回的是具有空值的A类对象。

A a; // value of a is null 
A x() {
    return a;
}

在跑步者班级

A a2=b.x(); // b.x() will return a, which is null. so A a2=null
a2.z();    // Equivalent to null.z() throws NullPointerException 

Class B代码中进行以下更改:

class B{
    A a;
    A x(){
    return new A();// return new object of Class A;   
    }
}

class B{
    A a= new A(); // Initialize Class A with new object 
    A x(){
    return a;   
    }
}