如何在a类方法中访问另一个类的属性

问题描述 投票:0回答:3

基本上,我想打印(robot_name“由”person_name拥有),其中robot_name是Robot类的属性,而person_name是Person类的属性。 我在名为 isOwnedby() 的类 Person 的方法中打印此内容

实际上,我想在名为 isOwnedby() 的类 Person 的函数中访问 Robot 类的 r1 对象的 rname 属性。但是,我遇到了以下错误,

错误:找不到符号 System.out.println(r1.rname() + "属于" + this.name); ^ 符号:变量r1 地点:Person班级

代码片段如下,

public class Main
{
    public static void main(String[] args) {
        //Robot class objects
        Robot r1 = new Robot("Jerry", "Red", 30);
        r1.introduceself();
        Robot r2 = new Robot("Tom", "Blue", 40);
        r2.introduceself();
        
        //Person class objects
        Person p1 = new Person("Alice", "Aggresive", false);
        Person p2 = new Person("Becky", "Talkative", true);
        p1.robotOwned = r2;
            p2.robotOwned = r1;
        
        p1.robotOwned.introduceself(); //same as r2.introduceself()
        p2.robotOwned.introduceself(); //same as r1.introduceself()
        p1.isOwnedby();
    }
}

class Robot 
{
    String rname;
    String color;
    int weight;
    
    //constructor
    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;
    
    //constructor
    Person (String n, String p, boolean i)
    {
        this.name = n;
        this.personality = p;
        this.isSitting = i;
    }
    
    
    //methods
    
    void isOwnedby()
    {
        System.out.println(r1.rname() + "is owned by" + this.name);
    }
      
    public String pname()
    {
        return name;
    }
}
java object oop generics methods
3个回答
1
投票

因此

r1
无法从
Person
类中访问,因为它没有在那里定义。您将需要使用本地
robotOwned
对象来代替:

private void isOwnedby() {
    System.out.println(robotOwned.rname() + "is owned by" + this.name);
}

其他建议:

  • 避免使用单字符变量名。描述性变量名称对每个人都更好。
  • 每个文件只有一个 Java 类通常是一个好主意。
  • delux247 有一个好主意,在尝试返回机器人的名称之前检查 null 。

0
投票

您的 Person 类不知道 r1 在行中指的是:

System.out.println(r1.rname() + "is owned by" + this.name);
因此,您需要做的是将机器人作为参数传递给方法“isOwnedby()”,例如:

void isOwnedby(Robot r1)
    {
        System.out.println(r1.rname() + "is owned by" + this.name);
    }

-1
投票

改变

System.out.println(r1.rname() + "is owned by" + this.name);

if(robotOwned != null){
  System.out.println(robotOwned.rname() + "is owned by" + this.name);
} else{
  System.out.println(this.name + " does not own a robot");
}
© www.soinside.com 2019 - 2024. All rights reserved.