简体   繁体   English

Java,将字符串从一个类传递到另一个类

[英]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 (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? 任何提示?

You need to create an instance of ApplesTestDrive , not Apples . 您需要创建ApplesTestDrive的实例,而不是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. 您正在Apple对象上调用方法paint但是paint方法在AppleTestDrive类中。

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. paint是ApplesTestDrive类的一种方法,而appleOne是一个Apples objject,所以你不能在这里调用appleOne.paint。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM