You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Person类方法中访问Robot类对象属性?遇找不到r1变量错误

问题解决:cannot find symbol: variable r1 错误

错误原因

r1是Main类中main方法的局部变量,作用域仅限main方法内部。Person类的isOwnedby()方法属于独立类的成员方法,无法直接访问外部方法的局部变量,因此编译报错。

你的代码中Person类已经定义了robotOwned成员变量,用来存储人物关联的机器人对象,这才是获取对应机器人名字的正确途径。

修复方案

修改Person类的isOwnedby()方法,通过robotOwned成员变量访问关联机器人的名字,同时注意字符串拼接时的空格,避免输出内容连在一起:

void isOwnedby() {
    // 直接访问机器人的rname属性,或调用你定义的rname()方法均可
    System.out.println(robotOwned.rname + " is owned by " + this.name);
}

完整修复代码

public class Main
{
    public static void main(String[] args) {
        //Robot类对象
        Robot r1 = new Robot("Jerry", "Red", 30);
        r1.introduceself();
        Robot r2 = new Robot("Tom", "Blue", 40);
        r2.introduceself();
        
        //Person类对象
        Person p1 = new Person("Alice", "Aggresive", false);
        Person p2 = new Person("Becky", "Talkative", true);
        p1.robotOwned = r2;
        p2.robotOwned = r1;
        
        p1.robotOwned.introduceself(); //等同于r2.introduceself()
        p2.robotOwned.introduceself(); //等同于r1.introduceself()
        p1.isOwnedby();
        p2.isOwnedby(); // 可添加此行测试p2的关联结果
    }
}

class Robot 
{
    String rname;
    String color;
    int weight;
    
    //构造方法
    Robot (String n, String c, int w)
    {
        this.rname = n;
        this.color = c;
        this.weight = w;
    }
    
    void introduceself()
    {
        System.out.println("My name is " + this.rname);
    }
    
    public String rname()
    {
        return rname;
    }
}

class Person
{
    String name;
    String personality;
    boolean isSitting;
    Robot robotOwned;
    
    //构造方法
    Person (String n, String p, boolean i)
    {
        this.name = n;
        this.personality = p;
        this.isSitting = i;
    }
    
    //成员方法
    void isOwnedby()
    {
        System.out.println(robotOwned.rname + " is owned by " + this.name);
    }
      
    public String pname()
    {
        return name;
    }
}

运行结果

执行代码后会输出:

My name is Jerry
My name is Tom
My name is Tom
My name is Jerry
Tom is owned by Alice
Jerry is owned by Becky

内容的提问来源于stack exchange,提问作者Nikhil Koshti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 19:25:32