java new对象带参数什么意思

来源:百度知道 编辑:UC知道 时间:2024/05/04 08:21:03
比如 A b=new A(String abc);
A b=new A("5");
总是不明白带参数的具体意义

当JVM创建一个对象时,首先都要初始化一遍,先从变量,然后构造函数,也就是没有返回值的方法,例如 A的构造函数是 public A(){},其中A可以带参数,也可以不带,你的例子中因为有参数所以A()要带参数 ,也就是public A(String s){},其实也就是为了初始化变量。如:
class A{
private String s;
public A(String s){
this.s = s;
}
}
创建对象是 A b=new A("5");
此时 b调用s的值就是5了;

带参数指调用对应带构造函数
比如你带A b=new A(String abc);
A类的定义
public class A{
String str;
int a;
public A(String str){
this.str=str;
}
public A(String str,int a){
this.str=str;
this.a=a;
}
.......................
}
一个类可能会有几个不同带构造函数,传带参数不同,可能调用的构造函数不同.

这是因为A类的“构造方法”中带有这个参数。
例如: class A{
A(String xxx){…………
}
}
class C{
……
public static void main(String[] args){
//A b=new A(String abc);可以是:A b=new A("abc");
A b=new A("5");

}
}
这儿所带的这个参数用来在A类中完成数值带传递等动作!!

你看来还是第一次接触JAVA,哈