开发者

Instantiation vs. Typed reference

Just when I think Im starting to understand the basics, I find something that brings me right back to reality. In this case, typed reference.

I found an example similar to this:

class Worker
{
Boss boss;

public void Advise(Boss pBoss)
{
    this.boss = pBoss;
}

How can you reference methods within the Boss class if its not static and not instantiated?

I guess my real question is wh开发者_StackOverflowats the difference between:

Boss boss;

and

Boss boss = new Boss();


Boss boss; creates a field called boss of type Boss (which has the value null by default).

Boss boss = new Boss(); creates a variable called boss of type Boss and stores a reference to a new instance of the type Boss in that variable.


Just having the code Boss boss; is only going to give you the ability to create a class of type Boss. When you instantiate the class using the code Boss boss = new Boss(); or by setting the variable this.boss = pBoss; in your Advise method, you will then be able to access methods and properties on your instantiated instance of the Boss object.


The field boss can contain a reference to an instance of the class Boss. Initially, boss contains null, meaning it doesn't reference any instance. Saying new Boss() creates a new instance of Boss. You can store a reference to this new instance in boss.

pBoss also can contain a reference to an instance of Boss, and you can store this reference in boss by saying boss = pBoss.


How can you reference methods within the Boss class if its not static and not instantiated?

You can't. Except for built-in datatypes like int, you always have to instantiate variables.

this.pBoss = Boss; only works when an object of type Boss has been instantiated somewhere else and is being passed into Advise() as an argument. If it had been called this way:

Advise(null);

...then you still couldn't use Worker.boss (it would throw an exception).

For what it's worth, this is more obvious in a lower-level language like C++.


The Advise() method takes an instance of the Boss class and then sets the private field to that instance of Boss. Once the Advise method has been called and the Boss instance set-up, the Worker class can then use any methods or properties the Boss exposes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜