Java, passing strings from one class to another
In below code i'm doing somthing wrong. Sorry if this is a bit basic. I get this working fine if it's all in the one class but not when i break the classes up like in the code below:
class Apples{
public static void main(String[] args){
String bucket = "green"; //instance variable
Apples appleOne = new Apples(); //create new object (appleO开发者_运维问答ne) from Apples class
System.out.println("Paint apple one: " + appleOne.paint(bucket));
System.out.print("bucket still filled with:" + bucket);
}//end main
}//end class
class ApplesTestDrive{
public String paint(String bucket){
bucket = "blue"; //local variable
return bucket;
}//end method
}//end class
Error Message:
location:class Apples
cannot find symbol
pointing to >> appleOne.paint(bucket)
Any hints?
You need to create an instance of ApplesTestDrive
, not Apples
. The method is in there.
So, instead of
Apples appleOne = new Apples();
do
ApplesTestDrive appleOne = new ApplesTestDrive();
This has nothing to do with passing by reference (so I removed the tag from your question). It's just a programmer error (as practically all compilation errors are).
You are calling the method paint on Apple object BUT the paint method is in AppleTestDrive class.
Use this code instead:
AppleTestDrive apple = new AppleTestDrive();
apple.paint(bucket);
System.out.println("Paint apple one: " + appleOne.paint(bucket));
paint is a method of ApplesTestDrive class and appleOne is an Apples objject, so you can't call appleOne.paint here.
精彩评论