java 调用类的方法而不创建它的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26270950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a method of a class without creating object of it
提问by user3690061
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
}
}
another example
另一个例子
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
As in above code i am calling z() method of class A with reference a2 without creating object of class A,As i am new to java i want to know which concept is this in java in the shown code ? for now i just know that if we want to call a method without creating object of it we have to make that method as static .
与上面的代码一样,我正在使用引用 a2 调用 A 类的 z() 方法,而不创建 A 类的对象,因为我是 Java 的新手,我想知道在显示的代码中这在 Java 中是哪个概念?现在我只知道如果我们想调用一个方法而不创建它的对象,我们必须将该方法设为静态。
in the second example using person reference found we are able to call displayPerson() method without null pointer exception
在使用 person 引用的第二个示例中,我们发现我们可以调用 displayPerson() 方法而不会出现空指针异常
回答by Darshan Lila
To call:
致电:
String z(){
System.out.println("a");
return "sauarbh";
}
without the object of the class A
the method z
has to be static:
如果没有类的对象,该A
方法z
必须是静态的:
static String z(){
System.out.println("a");
return "sauarbh";
}
So change your code as following:
所以改变你的代码如下:
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();
}
}
Output :
输出 :
a
回答by Ruchira Gayan Ranaweera
Yes without instantiate the class if you want to call the method you should use static
key word.
是的,如果要调用应该使用static
关键字的方法,则无需实例化该类。
What are you doing here?
你在这里做什么?
You are indirectly try to get instance of A
. But this case you will get NullPointerException
since you just return only a reference(variable) of A
您是间接尝试获取A
. 但是这种情况你会得到,NullPointerException
因为你只返回一个引用(变量)A
B b = new B();
A a2=b.x();
a2.z(); // NullPointerException from here
NPE?
NPE?
class B{
A a;
A x(){
return a; // you just return the reference
// it should be return new A();
}
}
For your edit:
对于您的编辑:
Take a look at insert()
method. It is creating Person
instance.
看一下insert()
方法。它正在创建Person
实例。
回答by Gautam Savaliya
Class B method x()
is not returning new object of A. Instead you are returning object of Class A with null value.
B 类方法x()
不返回 A 的新对象。相反,您返回的是具有空值的 A 类对象。
A a; // value of a is null
A x() {
return a;
}
In runner class
在跑步课上
A a2=b.x(); // b.x() will return a, which is null. so A a2=null
a2.z(); // Equivalent to null.z() throws NullPointerException
Make below changes in your Class B
code:
在您的Class B
代码中进行以下更改:
class B{
A a;
A x(){
return new A();// return new object of Class A;
}
}
or
或者
class B{
A a= new A(); // Initialize Class A with new object
A x(){
return a;
}
}