我正在从核心Java第1卷的书中学习Java,并且对java非常陌生.很抱歉标题令人困惑,但我不知道发生了什么。我写了一个程序,可以在屏幕上打印有关一个人的信息。所以我创建了一个 Man 类的对象数组:
这是我的男人课:-
package com.smit.man;
public class Man
{
private int age;
private long id;
private String name;
private double weight;
public Man(int aage,String aname,double aweight,long aid)
{
age =aage;
name = aname;
weight = aweight;
id = aid;
}
private Add add = new Add((name + "'s Shellter;"),(name + "'s hous's front road;"),(name + " colony;"),id+422);
public int getAge()
{
return age;
}
public long getId()
{
return id;
}
public String getName()
{
return name;
}
/**
* @return the weight
*/
public double getWeight()
{
return weight;
}
public void pall()
{
System.out.println
(
"Name = " +this.getName() +
" Age = "+this.getAge() +
" ID = " +this.getId() +
" Weight = "+this.getWeight()
);
add.pall();
System.out.println("nnn");
}
}
这个 Man 类使用 Add 类,它是这样的:-
package com.smit.man;
/**
* @author smit
*
*/
public class Add
{
private String shellterN,Rd,colony;
private long pin;
Add(String a,String b,String c,long d)
{
this.shellterN = a;
this.Rd = b;
this.colony =c;
this.pin = d;
}
public String getShellterN()
{
return shellterN;
}
public String getRd()
{
return Rd;
}
public String getColony()
{
return colony;
}
public long getPin()
{
return pin;
}
public void pall()
{
System.out.println("ShellterName = " + this.getShellterN() +
" Road = "+this.getRd()+
" Colony= "+ this.getColony()+
" PIN = " + this.getPin());
}
}
这是主要方法类:-
package com.smit.main;
import com.smit.man.*;
public class Mtest
{
public static void main(String[] args)
{
Man man [] = new Man[3];
man[0]= new Man(17,"Smit",55,34);
man[1] = new Man(100,"Master",60,400);
man[2] = new Man(200,"Guru",10,39);
for(Man a:man)
a.pall();
}
}
每当我在日食中运行它时,我都会得到以下输出
Name = Smit Age = 17 ID = 34 Weight = 55.0
ShellterName = null's Shellter; Road = null's hous's front road; Colony= null colony; PIN = 422
Name = Master Age = 100 ID = 400 Weight = 60.0
ShellterName = null's Shellter; Road = null's hous's front road; Colony= null colony; PIN = 422
Name = Guru Age = 200 ID = 39 Weight = 10.0
ShellterName = null's Shellter; Road = null's hous's front road; Colony= null colony; PIN = 422
我不想要这个空??为什么我得到这个空??
private Add add = new Add((name + "'s Shellter;"),(name + "'s hous's front road;"),(name + " colony;"),id+422);
此行位于构造函数之外,因此在创建对象时(甚至在构造函数之前)会立即调用它。您必须像所有其他变量一样添加到私有变量,并在构造函数的末尾对其进行初始化。
当调用此行时,该人的名字尚未初始化,因此为空。这就是造成问题的原因。
因为在构造函数执行之前,您要在Man
类中创建private add
类级成员。 只要类存在,就会执行类级实例化。 然后构造函数运行。 因此,name
成员在当时具有其默认值。
在构造函数中实例化name
值存在后的值:
private Add;
public Man(int aage,String aname,double aweight,long aid)
{
age =aage;
name = aname;
weight = aweight;
id = aid;
add = new Add((name + "'s Shellter;"),(name + "'s hous's front road;"),(name + " colony;"),id+422);
}