2014-10-09 5 views
-2
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 

Как и в приведенном выше коде я зову г() метод класса А с эталонным а2, не создавая объект класса A, Поскольку я новичок в java, я хочу знать, какая концепция это в java в показанном коде? пока я просто знаю, что если мы хотим вызвать метод без создания его объекта, мы должны сделать этот метод статическим.

во втором примере, используя лицо ссылку нашел, мы можем вызвать метод displayPerson() без исключения нулевого указателя

+1

'static' это ключевое слово вы ищете , –

+2

Вы получите исключение нулевого указателя, если у вас нет экземпляра 'A' ​​в классе' B'. –

+0

Вышеприведенный код должен вызывать исключение NullPointerException **, потому что ** вы никогда не создаете новый A внутри B. –

ответ

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

Я думаю, что 'A.z()' достаточно, если 'z' статично. –

+1

Чтобы добавить комментарий @TAsk, вам следует избегать вызова методов 'static' на ссылках, даже если они являются« нулевыми »ссылками и код запускается. –

+1

Это считается плохой практикой, вызывающей методы 'static' для переменных. Лучше просто сделать 'A.z()' –

0

Да без создания экземпляра класса, если вы хотите, чтобы вызвать метод следует использовать 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.

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; 
    } 
} 
Смежные вопросы