类级实例化与方法实例化之间的区别 [英] difference between class level instantiation vs method instantiation

查看:138
本文介绍了类级实例化与方法实例化之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下变量用法之间的区别

what is difference between following variable usages

public class A{

    B b= new B();

    public void doSomething()
    {
        b.callme();
    }
}

VS

public class A { 
    B b;
    public void doSomething() {
        b=new B(); 
        b.callme();
    }
}

如果我们在类中有单个b哪一个是更好的实践和为什么。

if we have single "b" inside a class then which one is better practice and why. and under what circumstances one whould be used.

推荐答案

这些实际上有非常不同的含义。在情况1中,当构建 A 时分配 b 对象。

These actually have very different meanings. In case 1, the b object is assigned when A is constructed. It is constructed once and only once (unless you are reassigning it from somewhere outside the class).

在情况2中,您将重新分配 A的 的实例每次调用方法

In case 2, you are reassigning A's instance of b every time the method is invoked

这篇关于类级实例化与方法实例化之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆