在另一个类JAVA中使用一个类的变量

时间:2016-12-10 12:55:52

标签: java class

我是java新手,我无法理解它。我应该如何在另一个类中使用一个类的变量

示例:我需要一个程序来添加2个数字。我想要一个输入类的输入,其他类中的main方法应该使用输入类中的变量来执行加法。 这是完全错误的如何纠正?

this wrong enter image description here

4 个答案:

答案 0 :(得分:1)

这是一个简单的例子:

B类

public class B {

    private int x;
    private int y;

    //constrictor of my class
    public B(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int addition(){
        //return the addition of x and y
        return this.x + this.y;
    }
}

A类

public class A {

    //main methode
    public static void main(String[] args) {
        int a, b;
        //You can use scanner to get values
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Number:");
        a = in.nextInt();
        System.out.println("Enter Number:");
        b = in.nextInt();

        //create a new object, and give it the values you want
        B b = new B(a, b);
        //print the result
        System.out.println("addition = " + b.addition());
    }
}

您可以详细了解Java here

您可以了解类和构造函数以及方法here

希望这可以帮到你。

答案 1 :(得分:0)

您可以在main方法所在的另一个类中创建输入类的对象,并通过objname.variablename

访问输入类的变量

答案 2 :(得分:0)

选修两门课程,A& B. 据我所知,你需要的是在B的主要方法中访问A中的变量。 要做到这一点,你有两种方法。一个是@MrLY在上面的答案中所描述的。我建议使用它,但还有其他一些方法。

我不打算给你准确的编码,因为最好找到自己查找代码的方法。

  1. 在A类中,将变量设置为public。 (公共变量可以从项目中的任何地方访问)说变量1&变量2

  2. 在B类主要方法中创建A类对象。(例如:A a = new A())

  3. 现在您只需通过其实例调用变量即可访问这两个变量。 (例如,如果需要为variable1赋值;

  4. a.variable1 =“要分配的值”)

    这很简单。

    重复使用@MrLY建议的方法更好。原因是它为您提供了数据封装。因为那时您可以决定在何处使用以及何时使用您的变量。

    看一下Here它会让你对java中的访问修饰符有所了解。

答案 3 :(得分:0)

这是另一个答案:

类添加

public class add {
    public static void main(String[] args) {
        int ans;
        input in = new input();
        //here you can set value at a and b to the other class
        in.readAandB();

        //now you get make your operation
        ans = in.a + in.b;
        System.out.println("result = " + ans);
    }
}

课程输入

import java.util.Scanner;

public class input {

    //declaration of your attribute
    public int a;
    public int b;

    //constructor of your class input
    public input(){
    }

    //function to put values in your attribute a and b
    public void readAandB(){
        //You can use scanner to init your values
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a :");
        a = scan.nextInt();
        System.out.print("Enter b :");
        b = scan.nextInt();
    }
}
相关问题