【问题标题】:How to access a variable of method of an another class?如何访问另一个类的方法变量?
【发布时间】:2020-07-15 01:57:14
【问题描述】:

实际上,我正在开发一个项目,在该项目中我必须访问另一个类的方法的变量,并且在我的项目中面临类似的情况,我无法返回该值。请任何人解决这个问题。

package com.company;

class aaa {
    int num1;
    public void val() { // data type can't be changed
        num1 = 100;
    }
}

class  bbb {
    public void Values() {
        int num = 100;
    }
}

public class Main extends bbb {
    public static void main(String[] args) {
        // write your code here
        aaa obj1 = new aaa();
        bbb abj2 = new bbb();
        System.out.println(obj1.num1); // wants to print value 100 here but 
                                      //without returning value from the function

    }
}

【问题讨论】:

  • 仅供参考:您可能想查看this
  • 这根本不可能。方法的变量仅在方法运行时存在。即使该方法在调用堆栈上,您也无法访问该变量。你到底想达到什么目的?

标签: java variables inheritance multiple-inheritance


【解决方案1】:

local 变量 num1 就是这样,本地的。它是在方法中创建的,因此范围是方法的范围。您需要创建一个名为 num1 的类成员。如果 num1 是公开的,您可以按照您想要的方式引用它。如果成员是私有的,你需要一个吸气剂。如果要返回值,则需要将 signaturevoid 更改为 int

我不容忍任何这种命名,只是保持简单。

public class AAA {
    private int num1;

    public int getNum1() {
        return num1;
    }
}
obj1.getNum1();

【讨论】:

    【解决方案2】:

    一旦这个变量在方法范围内,这是不可能的。做你需要的唯一方法是在类范围内创建一个变量。我不会做这样的事情,而是将变量创建为私有的,并改为使用 get 和 set 方法。

    package com.company;
    class  aaa{
    
        public int num1;
    
        public void val(){
            num1 = 100;
        }
    }
    class  bbb{
        public void Values(){
            int num = 100;
        }
    }
    public class Main extends bbb{
    
        public static void main(String[] args) {
        // write your code here
            aaa obj1 = new aaa();
            bbb abj2 = new bbb();
            System.out.println(obj1.num1); // now the variable is in public access
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-21
      • 2014-10-10
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多