accessing a method that belongs to another class

This still confuses me a bit since I have received conflicting advice:

When object A needs to invoke a method "doSomething();" that belongs to object B through a reference (not through inheritance), is it necessary to instanciate object B, or just declaring a reference to it:

class A{

B b;

b.doSomething();

}

class B{

doSomething();

}

OR:

class A{

B b=new B();

b.doSomething();

}

class B{

doSomething();

}

1) Are both examples the same?

2) what if class B belonged to a different package?

Many thanks for clearing this one for me.

[1031 byte] By [DeChristoa] at [2007-11-26 15:52:55]
# 1
Try it and see.
jverda at 2007-7-8 22:13:17 > top of Java-index,Java Essentials,New To Java...
# 2

okay, what you really need is an understanding of what an instance method is:

When you write a method that you do not declare static, it has access to all of the instance variables of that class. Now, if you have two instances of class B, they each have different copies of their instance variables.

It's like saying that a person has a name. You have a name. I have a different name. If I have a method that operates on a name, and I have a person object that refers to you, then it will operate on your name. If I have a person object that refers to me, it will operate on my name.

Now, if I have a person object that doesn't refer to anybody yet, whose name will it operate on?

It can't, because it doesn't refer to a person. Instead, it would throw an exception, so that you knew you had made a mistake.

- Adam

guitar_man_Fa at 2007-7-8 22:13:17 > top of Java-index,Java Essentials,New To Java...
# 3

Ok, got it.. yes, I see what you mean, I tried it with the following:

class Zoid{

public void doIt() {

System.out.println("Doin' it...");

}

}

public class Myfoo {

//static Zoid zee; //Try 3

public static void main(String[] args) {

Zoid zee = new Zoid();//Try 1

//Zoid zee; //Try 2

zee.doIt();

}

}

Thanks for the encouraging to try it! So, obviously trying Try1, Try2, Try3 indicidually, I know that I *must* instanciate the object from the class that I need to use the nethod from.... BTW a lot of code examples in various books just bypass this little detail and can get confusing to a newcomer..

DeChristoa at 2007-7-8 22:13:17 > top of Java-index,Java Essentials,New To Java...