Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, passing strings from one class to another

Tags:

java

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 (appleOne) 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?


2 Answers

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).

like image 97
BalusC Avatar answered Feb 14 '26 19:02

BalusC


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);
like image 45
Faisal Feroz Avatar answered Feb 14 '26 21:02

Faisal Feroz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!