[英]Constructor confusion Java
嗨,这似乎是一个非常愚蠢的问题,但是我最近接触了Java,并且自学了有关构造函数的知识。
public class creatures {
private static String name;
private static int age;
private static String type;
public creatures( String name, int age, String type) {
this.name = name;
this.age = age;
this.type = type;
System.out.println("The creature's name is " + name + " \nThe creatures age is" + age + " \nThe creatures type is " + type);
}
public static void main(String [] args) {
creatures newcreature = new creatures("Zack", 100, "alien");
creatures newcreature1 = new creatures("Jonny", 500, "vampire");
creatures newcreature2 = new creatures("Dick", 4, "witch");
System.out.println(newcreature.name);
}
}
因此,在我的主要方法中的system.out.println中,在构造函数被打印之后,我想通过引用我的newcreature构造函数的名称来打印名称“ Zack”,但是它只是从最后一个构造函数中打印名称“ Dick”我做的。 如何区分同一个类中的这些构造函数? 再次抱歉,如果这是一个愚蠢的问题。
因为您的名称字段是静态的,所以它共享一个公共内存。因此,如果您尝试通过用不同的对象来对其进行修饰来访问它,它将给出相同的输出。
自上次更改值以来, new creatures("Dick", 4, "witch");
与Dick
将改变它。
因此,删除static关键字即可获得所需的o / p
public class creatures {
private String name;
private int age;
private String type;
public creatures( String name, int age, String type) {
this.name = name;
this.age = age;
this.type = type;
System.out.println("The creature's name is " + name + " \nThe creatures age is" + age + " \nThe creatures type is " + type);
}
public static void main(String [] args) {
creatures newcreature = new creatures("Zack", 100, "alien");
creatures newcreature1 = new creatures("Jonny", 500, "vampire");
creatures newcreature2 = new creatures("Dick", 4, "witch");
System.out.println(newcreature.name);
}
}
产量
Zack
类的所有数据成员都是静态的,这就是每个实例共享同一成员的原因。 每当您创建生物的新实例时,构造函数都将用新值覆盖旧值。
在您的代码中:
private static String name;
private static int age;
private static String type;
在生物,生物1,生物2之间共享。
删除静态关键字。
public class creatures {
private String name;
private int age;
private String type;
public creatures(String name, int age, String type) {
this.name = name;
this.age = age;
this.type = type;
System.out.println("The creature's name is " + name
+ " \nThe creatures age is" + age + " \nThe creatures type is "
+ type);
}
public static void main(String[] args) {
creatures newcreature = new creatures("Zack", 100, "alien");
creatures newcreature1 = new creatures("Jonny", 500, "vampire");
creatures newcreature2 = new creatures("Dick", 4, "witch");
System.out.println(newcreature.name);
}
}
您的字段name
, age
和type
是静态的。 这意味着它们被您所有的生物共享。 因此,您不能说“此生物的名称为...”,因为该生物在您的代码中没有名称。 按照其编写的方式,您只能说“该生物类具有此名称...”,在Java中是这样写的creatures.name=...
。
因此,您需要从字段中删除该static
修饰符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.