什么方法来检查类的天气对象是否在Java中分配了类的实例?

Aks*_*ani 0 java oop class object

我只是用一小段大代码来解释我的问题:

class A 
{
    B b= new B();
    B z; 
    void xyz(){
        if(// condition to check z is not assigned instance of class B){
        z=b;
        }
        else{
        z= new B();
        }
    }
}

class B{
//variables and methods
}
Run Code Online (Sandbox Code Playgroud)

我想要一个表达式,如果xyz()的块检查天气对象z已经分配了一个B的实例,我在if块的括号中做了评论.或以其他方式.

什么是检查天气的方法任何java对象都有他们的类的实例?

Md.*_*yan 7

使用instanceof你可以检查一下

试试这个:

        B b= new B();
        B z = null; 
        if( z instanceof B){
           z=b;
           System.out.println("yes");
        } else{
           z = new B();
           System.out.println("no");
        }
Run Code Online (Sandbox Code Playgroud)