Java将值传递给类

时间:2016-01-31 18:14:58

标签: java

在搜索并阅读了很多关于在类/方法之间传递值/对象的例子后,我仍然没有得到它。 。 。 让我们说我有这个小代码(这是错误的):

public class Main{
    public static void main(String[] args){
        Print print = new Print();
    }
}

//主类的结尾

class ClassA{
    int x = 3;
    int y = 5;
    public classA(int a, int b){
        a = x;
        b = y;
    }
}
class ClassB{
    int c;
    public classB(int a, int b){
        c = a * b;
    }
}
class Print{
    int c;
    public Print(int c){
    System.out.println("C is equal to: " + c);
    }
}

这段代码示例不起作用,但我想一次又一次地理解传递值在java中是如何工作的。 谢谢。

4 个答案:

答案 0 :(得分:1)

在您实例Print时添加一些int值:

  Print print = new Print(445);

答案 1 :(得分:0)

构造函数必须与类的简单名称完全相同(没有包的类名)。区分大小写。在第4行使用public ClassA代替public classA

变量分配采用以下语法:

{target_to_assign_to} = {value_to_assign};

你正在采取相反的方式。

此外,您必须将值传递给Print()构造函数,正如@Abdelhak指出的那样。

答案 2 :(得分:0)

  

打印print = new Print();

在上面的语句中,您尝试调用默认构造函数。当您定义自己的构造函数时,这将变得不可用。因此要么定义一个默认构造函数,要么传递一个值。

Print print = new Print(10);

OR

class Print{
    int c;
    public Print(int c){
    System.out.println("C is equal to: " + c);
    }
    public Print(){
    System.out.println(" Handles : new Print() ");
    }

}

答案 3 :(得分:0)

首先,你从不调用ClassA和ClassB(你还必须编写类似于它的类的构造函数;所以ClassA而不是classA),所以你基本上可以删除它们。

现在关于传递值。你实际上从未传递过一个值。创建对象时,可以将参数传递给对象所属类的构造函数。因此,当您在Main类中创建一个新的Print对象时,您必须为Print类的构造函数传递一个值。

Print print = new Print(5); //5 is the value you pass

另一件可能让您感到困惑的事情是:在Print类中设置int c,这意味着它作为属性。您创建的每个Print对象都有一个int,您可以通过printObject.c访问该对象,例如您可以编写

Print print = new Print(5); // Sets your locale variable c for printing it to 5
print.c = 5; // Sets the attribute c to 5

如果你用不同的名字命名,那就不那么容易了。像这样:

class Print {
  int myInt;
  public Print(int c){
    System.out.println("C is equal to: " + c);
  }
}

如果您确实想将属性myInt(您将其称为c)设置为传递给构造函数的值,则代码将如下所示:

class Print{
  int myInt;
  public Print(int c){
    this.myInt = c; // Sets the value of the attribute myInt to the value of c
    System.out.println("C is equal to: " + c); // Prints out the value you passed
  }
}